我最近開始Android應用程序的開發,並已運行到一個問題,我無法找到一個解決方案。如何刪除正確的片段實例的Android
當用戶按下按鈕時,增加了活性的片段插入表中。然後,用戶可以根據自己想要(每一個顯示出來對錶中的一個新行)添加此片段的多個實例。這工作完美。
問題是當用戶點擊一個按鈕刪除的片段。每個片段都有自己的刪除按鈕,但無論是哪一個用戶點擊,底行總是被刪除。我如何讓它刪除正確的片段?
以下是所有相關代碼,包括碎片的創建。如果我做了錯誤的創建,請告訴我,告訴我,我應該怎麼做。
解釋一些語法會發生什麼會非常有幫助!
主要活動:
public class WorkingOut extends AppCompatActivity {
private int numOfSets = 0;
private static FragmentManager fm;
...
private void initialize(){
...
fm = getSupportFragmentManager();
}
public void addSet(View view) {
WorkoutSets newSet = new WorkoutSets();
fm.beginTransaction().add(R.id.set_container, newSet, "set_" + numOfSets).addToBackStack(null).commit();
}
public static void removeSet(String tag){
Fragment frag = fm.findFragmentByTag(tag);
fm.beginTransaction().detach(frag).commit();
//fm.beginTransaction().remove(frag).commit();
}
片段的活動:
public class WorkoutSets extends AppCompatDialogFragment {
public WorkoutSets() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_workout_sets, null);
Button button = (Button) view.findViewById(R.id.delete_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WorkingOut.removeSet(getTag());
}
});
return view;
}
@Override
public void onDetach() {
super.onDetach();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
主要活動表XML:
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/rest_for_message"
android:layout_marginTop="10dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/set_parent"
android:fadeScrollbars="false">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/set_container"
android:minHeight="10dp">
</TableLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Set"
android:id="@+id/add_set"
android:onClick="addSet"
android:layout_centerHorizontal="true"
android:layout_below="@+id/set_container"
android:layout_marginBottom="10dp"/>
</RelativeLayout>
</ScrollView>
片段刪除按鈕XML:
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="45dp"
android:layout_height="wrap_content"
android:text="x"
android:id="@+id/delete_button"
android:layout_marginLeft="10dp"
android:layout_centerVertical="true"/>
FIXED
下面的兩個解決方案都有效。 我覺得有點愚蠢,因爲我專門設置的標籤系統,使每個會都有自己的標籤,然後忘了增加它-_-」 多虧了兩個答案。