实现点击导航任意按钮,跳转到相对应的界面,实现方法可以用viewpage+fragment,还有就是用到hide,show,一般倾向于第二种,比较节省空间
xml界面:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<FrameLayout
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="myfrag"
android:text="我的" />
<Button
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="wxfrag"
android:text="微信" />
<Button
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="frfrag"
android:text="好友" />
<Button
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="findfrag"
android:text="发现" />
</LinearLayout>
</LinearLayout>
创建四个fragment界面,重写onCreateView()加载布局,此处省略
主代码:
/*
* 页面转换改良代码,避免切换页面时,前一个页面被销毁,
* 改良后,切换页面时,只是把前一个页面隐藏起来,需要时在显示出来
*/
public class MainActivity extends FragmentActivity {
private MyFrag f1;
private WeiXin f2;
private Friend f3;
private Find f4;
// 设置变量
private Fragment currentFragement;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (f1 == null) {
f1 = new MyFrag();
}
setFrag(f1);
}
// 监听方法
public void myfrag(View v) {
// 防止多次创建对象,重复添加,只创建一次
if (f1 == null) {
f1 = new MyFrag();
}
setFrag(f1);
}
public void wxfrag(View v) {
if (f2 == null) {
f2 = new WeiXin();
}
setFrag(f2);
}
public void frfrag(View v) {
if (f3 == null) {
f3 = new Friend();
}
setFrag(f3);
}
public void findfrag(View v) {
if (f4 == null) {
f4 = new Find();
}
setFrag(f4);
}
// 动态加载fragment方法
public void setFrag(Fragment fr) {
// 通过管理器获得事务
FragmentTransaction action = getSupportFragmentManager()
.beginTransaction();
// 隐藏前一个fragment
if (currentFragement != null) {
action.hide(currentFragement);
}
// 判断fragment是否被添加过,一个fragment只能提交一次,所以当第二次点击同一个
// button时,要判断一下是否添加过,如果添加过就不在添加,如果没添加过就添加
if (!fr.isAdded()) {
action.add(R.id.layout, fr);
} else {
action.show(fr);
}
// 提交
action.commit();
// 记录当前的fragment
currentFragement = fr;
}
}
许多的App都会用到此功能,以上代码就可以实现点击任意按钮跳转到相对应的界面,其实很简单