[英]New fragment on button click from another fragment?
can anyone point me in the right direction and tell me what I'm doing wrong? 谁能指出我正确的方向并告诉我我做错了什么?
I have here a fragment with a button. 我这里有一个带有按钮的片段。 When the button is pressed, it needs to replace the current fragment and load a new one. 当按下按钮时,它需要替换当前片段并加载一个新片段。 I've figured how to go from Fragment to Activity, and Activity to Fragment, just not Fragment to Fragment. 我已经弄清楚了如何从Fragment到Activity,以及从Activity到Fragment,而不是从Fragment到Fragment。 I'm aware this question has been asked a few times but I'm just so new I couldn't figure it out myself. 我知道这个问题已经问过几次了,但是我太新了,我自己都无法解决。
public class FragmentName extends Fragment {
public FragmentName() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_name, container, false);
Button ID = (Button) rootView.findViewById(R.id.buttonID);
ID.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentName NAME = new FragmentName();
fragmentTransaction.replace(R.id.main_container, NAME);
fragmentTransaction.commit();
}
});
return rootView;
}
}
I think you are not initialising the FragmentManager. 我认为您没有初始化FragmentManager。 Without FragmentManager it is not possible to replace,update,create any fragment. 没有FragmentManager,将无法替换,更新,创建任何片段。 Beacuse it is responsible replace or deleting any fragment. 因为它负责替换或删除任何片段。 Hope this will help. 希望这会有所帮助。
public class FragmentName extends Fragment {
public FragmentName() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_name, container, false);
Button ID = (Button) rootView.findViewById(R.id.buttonID);
ID.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentName NAME = new FragmentName();
fragmentTransaction.replace(R.id.main_container, NAME);
fragmentTransaction.commit();
}
});
return rootView;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.