多个Fragment在一个activity中通过按钮的展示方法

时间:2022-07-08 16:49:35

fragment使用方法

1. 创建主Mainactivity extends AppCompatActivity

2. Oncreate & setContentView

3. 完成XML的配置,包含两个部分,底部栏三个按钮及上边的content_view,注意都要加id(用来放接下来的的fragment)

4.创建3个fragment的layout xml页面

5. 创建fragment package,里面放3个fragment的页面,注意继承V4的Fragment,并修改return inflater

public class fragment_main extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main,container,false);
}
}

6. 在Mainactivity中初始化 3个fragment的java和xml
LinearLayout menu_Main;
LinearLayout menu_Middle;
LinearLayout menu_Menu;
protected fragment_main FragmentMain = new fragment_main();
protected fragment_menu FragmentMenu = new fragment_menu();
protected fragment_middle FragmentMiddle = new fragment_middle();

7. 将几个fragment页面添加到mainactivity中,并设置展示哪个,hide哪个
this.getSupportFragmentManager()
.beginTransaction()
.add(R.id.contain_con,FragmentMain)
.add(R.id.contain_con,FragmentMiddle)
.hide(FragmentMiddle)
.add(R.id.contain_con,FragmentMenu)
.hide(FragmentMenu)
.commit();

8. 初始化3个Xml页面并findbyid,若使用implement,则初始化监听
private void initView() {
menu_Main=findViewById(R.id.menu_main);
menu_Menu=findViewById(R.id.menu_menu);
menu_Middle=findViewById(R.id.menu_middle);

menu_Main.setOnClickListener(this);
menu_Menu.setOnClickListener(this);
menu_Middle.setOnClickListener(this);
}

9. implement或内部类方法设置监听

10 在监听方法中使用switch方法,点击哪个按钮就展示哪个fragment,并注意之前添加过fragment,所以只需设置show和hide。
switch (v.getId())
{
case R.id.menu_main:
this.getSupportFragmentManager()
.beginTransaction()
.show(FragmentMain)
.hide(FragmentMiddle)
.hide(FragmentMenu)
.commit();
break;
case R.id.menu_middle:
this.getSupportFragmentManager()
.beginTransaction()
.hide(FragmentMain)
.show(FragmentMiddle)
.hide(FragmentMenu)
.commit();
break;
case R.id.menu_menu:
this.getSupportFragmentManager()
.beginTransaction()
.hide(FragmentMain)
.hide(FragmentMiddle)
.show(FragmentMenu)
.commit();

break;
}