<--------------先看效果图-------------------->
就是实现这种切换的界面
开始实现吧
布局--> 就是一个相对布局中有一个ImageView用来放按钮,下面是FrameLayout用来展示要切换的Fragment
<RelativeLayout android:id="@+id/mainHead" android:layout_width="match_parent" android:layout_height="48dp" android:layout_alignParentTop="true" android:background="@drawable/bg_home_header1" android:orientation="horizontal"> <ImageView android:id="@+id/userImage" android:layout_width="40dp" android:layout_height="40dp" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:background="#ffffff" android:src="@drawable/myshifu" /> <ImageView android:id="@+id/mainTitle" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_centerInParent="true" android:src="@drawable/main_title_drawable" /> </RelativeLayout> <FrameLayout android:id="@+id/flContent" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/mainHead"></FrameLayout>
其中有ImageViewsrc的drawable 为一个selecter 是两个图片 为这个imageview设置切换图片的
selecter代码如下:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/header_switch_haitao" android:state_selected="false"></item> <item android:drawable="@drawable/header_switch_biji" android:state_selected="true"></item> </selector>
其次就是Java代码了
首先得到ImageView控件,并实现点击事件,通过TransAction的 Add、Show、Commit 设置默认显示的fragment,并通过点击imageview实现切换当前fragment
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mainHead = (RelativeLayout) findViewById(R.id.mainHead); mainTitle = (ImageView) findViewById(R.id.mainTitle); final BijiFragment bijiFragment = new BijiFragment(); final HaitaoFragment haitaoFragment = new HaitaoFragment(); //开启一个新的TransAction事件 FragmentTransaction action = getSupportFragmentManager().beginTransaction(); action.add(R.id.flContent, bijiFragment); action.show(bijiFragment); action.commit(); mCurrentFragment = bijiFragment; //设置默认 mainTitle.setSelected(true); mainTitle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!mainTitle.isSelected()) { mainTitle.setSelected(true); showFragment(bijiFragment); } else { mainTitle.setSelected(false); showFragment(haitaoFragment); } } });
代码中showFragment() 为一个显示Fragment的方法
具体如下
//展示Fragment的方法 private void showFragment(Fragment fragment) { FragmentTransaction action = getSupportFragmentManager().beginTransaction(); if (null != mCurrentFragment) { action.hide(mCurrentFragment); } mCurrentFragment = fragment; //判断这个Fragment是否已经添加进了transaction事物中 if (!fragment.isAdded()) { action.add(R.id.flContent, fragment); } else { action.show(fragment); } action.commit(); }