3:MainActivity代码详情
package cn.cg.wechat;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity {
private Fragment weChat,contacts,discover,myMessage;
private FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InintView();
findViewById(R.id.btn_wechat).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragmentManager.beginTransaction().replace(R.id.frameLayout,weChat).commit();
}
});
findViewById(R.id.btn_contacts).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragmentManager.beginTransaction().replace(R.id.frameLayout,contacts).commit();
}
});
findViewById(R.id.btn_discover).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragmentManager.beginTransaction().replace(R.id.frameLayout,discover).commit();
}
});
findViewById(R.id.btn_mymessage).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragmentManager.beginTransaction().replace(R.id.frameLayout,myMessage).commit();
}
});
}
//初始化操作
private void InintView() {
//【1】实例化Fragment的实例对象:weChat,contacts,discover,myMessage为Fragment对象
weChat=new WeChatFragment();
contacts=new ContactsFragment();
discover=new DiscoverFragment();
myMessage=new MyMessageFragment();
//这个已经不在维护,不推荐使用
// fragmentManager=getFragmentManager();
//【2】获得FragmentManager(Dragment管理器)对象
fragmentManager=getSupportFragmentManager();
//【3】开启事务
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
//【4】向Activity的布局容器(一般为FrameLayout)中添加Fragment
fragmentTransaction.replace(R.id.frameLayout,weChat);
//【5】提交事务
fragmentTransaction.commit();
}
}
向Activity的布局容器(一般为FrameLayout)中添加Fragment除了replace()还有add()方法
replace()和add()的区别我在网上随便找了一篇,链接入下
Fragment中replace和add的区别
4:运行效果
原创文章 78获赞 26访问量 9633
关注
私信
展开阅读全文
作者:一位爱猫的程序员