[英]How to click and add another Fragment in one Fragment?
如何在一個片段中單擊並添加另一個片段?
單擊按鈕可在一個活動中添加片段。 firstFragment中還有另一個按鈕。 我想單擊按鈕並添加secondFragment。 怎么實現這個?
提前致謝!
在Fragment1中,使用按鈕擴展XML布局。 設置按鈕的onClickListener並定義onClick方法。
// In Fragment1...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layoutWithButton, container, false);
Button b = (Button) view.findViewById(R.id.myButton);
b.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.layoutWithButton:
Fragment fragment2 = new Fragment2;
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment2); // where container is the FrameLayout where Fragment 1 was first placed
transaction.commit();
break;
default:
break;
}
根據您希望如何處理后台堆棧,您可以包含transaction.addToBackStack(null);
如所須。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.