我片段中的代码结构如下:
public class FragmentScanQR extends Fragment {
...
private Button qrFromCameraBtn;
private View rootView;
...
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.qrsource, container, false);
qrFromCameraBtn = (Button)rootView.findViewById(R.id.qrViaCameraBtn);
qrFromCameraBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
rootView = inflater.inflate(R.layout.fragmenttab1, container, false);
}
});
return rootView;
}
片段的onCreateView
方法返回android.view.View类型的值。 qrFromCameraBtn
按钮的onClick
方法修改了相同的View变量。在输出中,当我单击按钮时,布局不会更改为R.layout.fragmenttab1
(我希望实现),但保持不变。我怎么能这样做?
答案 0 :(得分:2)
如果我了解您的需要,您想要用新的片段替换您的第一个片段。你可以这样做:
//Where Article fragment is your new fragment.
ArticleFragment newFragment = new ArticleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
来源:https://developer.android.com/training/basics/fragments/fragment-ui.html
答案 1 :(得分:0)
如果您只想更换布局,此链接可能会对您有所帮助。 Android - How to dynamically change fragment layout。 只需在按钮单击方法
上添加以下代码即可 qrFromCameraBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout rl = (RelativeLayout) findViewById(R.id.about);
rl.removeAllViews();
rl.addView(View.inflate(myView.getContext(), R.layout.about, null));
}
});