这个问题百度了很多能用的很少!
原来看的B站的视频教程比较老了参数不匹配!我记一下安卓studio3.1的方法
切换fragment 前都先要 FragmentManager manager=getSupportFragmentManager() //这个是 android.support.v4.app.FragmentManager;
然后FragmentTransaction transaction=manager.beginTransaction(); 之后执行 transaction.replace(fragment 的id); 最后 transaction.commit();
感觉一般主窗口载入窗口你会Add一个fragment 之后点击切换的时候 程序就会崩溃!!!! 你要在载入你fragment 前面加入 transaction=manager.beginTransaction();不管你载入那个fragment 都加这一句
代码如下写的很low 凑合看
主窗口代码
package com.stdu.myllogin; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView zhanghaodenglu; private TextView dongtaimimadenglu; private FragmentManager manager; private FragmentTransaction transaction; private YanZhengMaFragment yanZhengMaFragment; private LoginFragment loginFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); loginFragment=new LoginFragment(); manager= getSupportFragmentManager(); transaction=manager.beginTransaction(); transaction.replace(R.id.login_frea,loginFragment); transaction.commit(); zhanghaodenglu=findViewById(R.id.zhanghao_login); dongtaimimadenglu=findViewById(R.id.mima_login); zhanghaodenglu.setOnClickListener(listener); dongtaimimadenglu.setOnClickListener(listener); yanZhengMaFragment=new YanZhengMaFragment(); loginFragment=new LoginFragment(); } private View.OnClickListener listener=new View.OnClickListener() { @Override public void onClick(View view) { switch (view.getId()) { case R.id.mima_login: hideFragment(transaction); //transaction.remove(loginFragment); transaction=manager.beginTransaction();//这里一定要再写一遍 否则会出错 transaction.replace(R.id.login_frea,yanZhengMaFragment); transaction.commit(); // Toast.makeText(MainActivity.this,"验证码登陆测试",Toast.LENGTH_SHORT).show(); break; case R.id.zhanghao_login: hideFragment(transaction); transaction=manager.beginTransaction();//这里一定要再写一遍 否则会出错 transaction.replace(R.id.login_frea,loginFragment); transaction.commit(); //Toast.makeText(MainActivity.this,"账号登陆测试",Toast.LENGTH_SHORT).show(); break; } } }; private void hideFragment(FragmentTransaction transaction) { if (loginFragment != null) { transaction.remove(loginFragment); } if (yanZhengMaFragment != null) { transaction.remove(yanZhengMaFragment); } } }
布局界面不写了看看我的哈皮运行截图吧