记录一下底部导航栏功能的实现,一个简单的Fragment页面切换过程
原理
步骤:
效果图
项目结构图
原理
通过给底部四个LinearLayout设置监听器,利用findViewById()找到所有view,获取FragmentManager
工具:Android Studio
步骤:
1:在MainActivity所属包下创建四个Java.class文件,例如图中的Fragment1,Fragment2。
2:可在底部添加小图标,图标推荐下载网址www.easyicon.net,下载完成后直接复制粘贴在drawable目录下,例如图中的a.png,b.png。
3:在layout中新建四个.xml文件,以此来显示点击后的界面(注意:图中的layout_main是新建的布局文件,有时用系统自动创建的activity_main文件时会导致添加的控件无法显示)
MainActivity代码
package com.example.hp.weixin;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private LinearLayout lin1,lin2,lin3,lin4;
private ImageView iva,ivb,ivc,ivd,ivCurrent;
private TextView weixin,tongxunlu,finding,me,tvCurrent;
private FragmentManager fragmentManager;
private FragmentTransaction beginTransaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.layout_main);
lin1 = (LinearLayout) findViewById(R.id.lin1);
lin2= (LinearLayout) findViewById(R.id.lin2);
lin3 = (LinearLayout) findViewById(R.id.lin3);
lin4 = (LinearLayout) findViewById(R.id.lin4);
lin1.setOnClickListener(this);
lin2.setOnClickListener(this);
lin3.setOnClickListener(this);
lin4.setOnClickListener(this);
iva = (ImageView) findViewById(R.id.iva);
ivb = (ImageView) findViewById(R.id.ivb);
ivc = (ImageView) findViewById(R.id.ivc);
ivd = (ImageView) findViewById(R.id.ivd);
weixin = (TextView) findViewById(R.id.weixin);