我最近开始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
下面的两个解决方案都有效。 我觉得有点愚蠢,因为我专门设置的标签系统,使每个会都有自己的标签,然后忘了增加它-_-” 多亏了两个答案。