我无法在这里使用大多数解决方案。请检查我在活动中启动片段的代码。
public void selectFrag() {
Fragment fr;
fr = new SelectionFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
//I removed this since my animations give error with FrameLayout
//fragmentTransaction.setCustomAnimations(R.anim.slide_in_up, R.anim.slide_out_down);
fragmentTransaction.replace(R.id.fragment_selection, fr);
fragmentTransaction.commit();
}
在我的片段中,我有以下内容正在扩展android.support.v4.app.Fragment;
public class SelectionFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
View view = inflater.from(getActivity()).inflate(
R.layout.fragment_attributes, container, false);
//Close fragment using close icon
ImageView close = (ImageView) view.findViewById(R.id.close_fragment);
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
closefragment();
}
});
return view;
}//End onCreateView Method
private void closefragment() {
getActivity().getFragmentManager().popBackStack();
}
}
我的XML在RelativeLayout
中包含ImageView<ImageView
android:id="@+id/close_fragment"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:paddingTop="3dp"
android:paddingRight="3dp"
android:src="@drawable/close_cross"/>
如何设置ImageView以侦听关闭片段的点击?我只有一个片段,上面的代码没有任何反应。
答案 0 :(得分:3)
从closefragment()
中删除getActivity()
private void closefragment() {
getFragmentManager().popBackStack();
}
答案 1 :(得分:1)
解决方案如下:
fragmentTransaction.replace(R.id.fragment_selection, fr);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();`
答案 2 :(得分:0)
popBackStack();只会撤消您之前的交易。如果你想关闭这个片段,你应该打电话给
getActivity().getFragmentManager().beginTransaction().remove(this).commit();
答案 3 :(得分:0)
试试这个。
private void closefragment() {
getParentFragment().getFragmentManager().popBackStack(); }
或者
private void closefragment() {
getActivity.finish(); }