/**
* Created by zxn on 2016/7/31.
* 说明:主界面下方有四个Button,上方为Fragment,点击四个Button会跳转相应的Fragment。Demo
*/
public class FarmMainActivity extends Activity implements View.OnClickListener
{
//这里有四个Fragment布局。四个类继承Fragment,各自引用自己的布局
//例:public class Fragment_A_activity extends Fragment
Fragment_A_activity fragmenta;
Fragment_B_activity fragmentb;
Fragment_C_activity fragmentc;
Fragment_D_activity fragmentd;
@Override
protected void onCreate(Bundle savedInstanceState)
{
//主界面布局
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_farmmain);
FragmentManager fragmentMtext = getFragmentManager(); //Fragment管理器
FragmentTransaction transactiontext = fragmentMtext.beginTransaction();//开启事务
//设置第一个Fragment。APP启动主界面显示的第一个Fragment
if (fragmenta == null)
{
fragmenta = new Fragment_A_activity();
transactiontext.add(R.id.frameLayout, fragmenta);
} else
{
transactiontext.show(fragmenta);
}
transactiontext.commit();
}
//给按键添加OnClick以及ID,可以在这边监听
@Override
public void onClick(View view)
{
FragmentManager fragmentManager = getFragmentManager(); //Fragment管理器
FragmentTransaction transaction = fragmentManager.beginTransaction();//开启事务
hide(transaction);//隐藏所有的Fragment
switch (view.getId())
{
//当第一个按钮按下,显示第一个Fragment页面
case R.id.btn1:
{
if (fragmenta == null)
{
fragmenta = new Fragment_A_activity();
transaction.add(R.id.frameLayout, fragmenta);
} else
{
transaction.show(fragmenta);
}
break;
}
//当第二个按钮按下,显示第二个Fragment页面
case R.id.btn2:
{
if (fragmentb == null)
{
fragmentb = new Fragment_B_activity();
transaction.add(R.id.frameLayout, fragmentb);
} else
{
transaction.show(fragmentb);
}
break;
}
//当第三个按钮按下,显示第三个Fragment页面
case R.id.btn3:
{
if (fragmentc == null)
{
fragmentc = new Fragment_C_activity();
transaction.add(R.id.frameLayout, fragmentc);
} else
{
transaction.show(fragmentc);
}
break;
}
//当第四个按钮按下,显示第四个Fragment页面
case R.id.btn4:
{
if (fragmentd == null)
{
fragmentd = new Fragment_D_activity();
transaction.add(R.id.frameLayout, fragmentd);
} else
{
transaction.show(fragmentd);
}
break;
}
}
transaction.commit();
}
//设置隐藏
private void hide(FragmentTransaction transaction)
{
if (fragmenta != null)
{
transaction.hide(fragmenta);
}
if (fragmentb != null)
{
transaction.hide(fragmentb);
}
if (fragmentc != null)
{
transaction.hide(fragmentc);
}
if (fragmentd != null)
{
transaction.hide(fragmentd);
}
}
}
按键监听实现Fragment跳转
最新推荐文章于 2022-08-30 14:06:39 发布
本文介绍了一个简单的Android应用案例,该应用包含四个按钮和一个Fragment容器。点击不同的按钮将加载对应的Fragment,通过Fragment管理器和事务操作实现了Fragment的切换与显示。
摘要由CSDN通过智能技术生成