任何人都可以指出我正确的方向并告诉我我做错了什么吗?
我这里有一个带按钮的片段。按下按钮时,需要替换当前片段并加载新片段。我已经想过如何从片段到活动,从活动到碎片,只是没有碎片到片段。我知道这个问题已被问过几次了,但我只是这么新,我无法自己解决这个问题。
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;
}
}
答案 0 :(得分:0)
我认为你没有初始化FragmentManager。没有FragmentManager,就无法替换,更新,创建任何片段。因为它负责替换或删除任何片段。希望这会有所帮助。
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;
}
}