问题描述
当前,我的主要活动有一个描述字段,当用户单击描述时会打开一个片段.在片段上有一个文本字段和一个按钮,当我单击该按钮时,我想关闭片段并返回到我的活动.
Currently, my main activity has a description field which opens a fragment when the user clicks on the description. On the fragment there is a text field and a button, when I click the button, I want to close the fragment and go back to my activity.
我该如何实现?
我已经在片段中添加了onClickListener来捕获对按钮的单击.吐司消息被打印,但是片段没有被移除/关闭.
I have added an onClickListener to my fragment to capture the click on the button. The toast message gets printed, but the fragment is not removed/closed.
descDismiss.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), "Dismissed", Toast.LENGTH_LONG).show();
getActivity().getFragmentManager().popBackStackImmediate();
}
});
我在片段的onCreateView中有onClickListener.这是正确的吗?
I have the onClickListener in the onCreateView of the fragment. Is this correct?
提前谢谢!
我正在添加这样的片段:
I am adding my fragment like this:
((MainActivity)context).getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, frag).commit();
推荐答案
首先尝试将片段像这样添加到Backstack中
try this first add the fragment to backstack like this
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(..............);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
然后像这样删除片段:-
Then remove the fragment like this:-
FragmentManager fm = getActivity().getSupportFragmentManager();
if(fm.getBackStackEntryCount()>0) {
fm.popBackStack();
}
删除所有碎片
FragmentManager fm = getActivity().getSupportFragmentManager();
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
这篇关于单击按钮时从活动中删除片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!