【发布时间】:2014-10-16 11:56:51
【问题描述】:
我的问题是我想从 Activity 中删除 Fragment。有两个步骤:
- 通过检查
CheckBox将Fragment添加到FrameLayout(R.id.frame_for_des_details)。 -
通过单击
TextView删除Fragmentpublic class CreateTripActivity extends FragmentActivity { //Vars for Destination Fragment private CheckBox checkBox; private DestinationDetailsFragment destinationDetailsFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Setting the ContentView setContentView(R.layout.activity_create_trip); //Set the Destination Checkbox listener checkBox = (CheckBox) this.findViewById(R.id.checkBox_destination_now);
CheckBox 的监听器:
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//Adding the Fragment. THIS WORK
destinationDetailsFragment = new DestinationDetailsFragment();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().add(R.id.frame_for_des_details, destinationDetailsFragment).commit();
}
});
TextView 的监听器:
findViewById(R.id.label_later).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Removing the Fragment. DOES NOT WORK
FragmentManager fm = getFragmentManager();
fm.beginTransaction().remove(destinationDetailsFragment).commit();
}
});
}
当我检查CheckBox 时,我可以看到片段。但是当我单击TextView 将其删除时,它仍然存在。
当我一次又一次地检查CheckBox 时,似乎新的Fragment 覆盖了旧片段,因此我可以在EditText 中覆盖占位符。
我希望有人理解我并可以帮助我。
谢谢。
【问题讨论】:
-
你检查过你的 textview 的 onClick 是否真的被触发了吗?可以肯定的是,您可以在该方法中打印日志以查看它是否到达那里。顺便说一句,使用 TextView 的 onClicklistener 来删除片段并不是一个好主意。
-
@elvisrusu 如果有人使用支持库中的
Fragment,则需要使用支持片段管理器。android.app.Fragment和android.support.v*.Fragment是两个不同的野兽。你不能把这两件事混为一谈。 -
尝试将
android:clickable="true"添加到TextView
标签: android android-fragments checkbox fragment