首先应应该在MainActy添加Fragment,使用
getFragmentManager().beginTransaction().add(R.id.container,new BlankFragment1()).commit();这句话即可,container是主布局的ID,后者是新的Fragment类
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(savedInstanceState==null){ getFragmentManager().beginTransaction().add(R.id.container,new BlankFragment1()).commit(); } } }之后,就是重写BlankFragment1的onCreateView函数,使用inflater.inflate函数获取BlankFragment的布局文件,然后再对其内部进行操作
@Override public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView=inflater.inflate(R.layout.fragment_blank_fragment1,container,false); rootView.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getFragmentManager().beginTransaction().replace(R.id.container,new BlankFragment2()).commit(); } }); return rootView; }
<Button android:layout_width="wrap_content" android:layout_height="142dp" android:text="呈现另一个Fragment" android:id="@+id/button" android:layout_gravity="center_horizontal" />
同时可以使用AddToBackStack()函数,和按钮点击使用PopBackStack()来实现Fragment的后退键
public void onClick(View v) { getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container,new BlankFragment2()).commit(); } });
View rootView=inflater.inflate(R.layout.fragment_blank_fragment2,container,false); rootView.findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getFragmentManager().popBackStack(); } }); return rootView;