1. 程式人生 > >三種方式實現Android頁面底部導航欄

三種方式實現Android頁面底部導航欄

我們在Android手機上使用新浪微博和QQ等一些軟體時,經常會遇到類似下面這種頁面底部導航欄的控制元件,使用這種導航欄可以在手機螢幕的一頁中顯示儘可能多的內容,如下圖所示:

下面我將實現這種導航欄的三種方法總結如下:

一、使用TabHost實現(TabHost在新版的Android SDK中已經不推薦使用了,但是這裡還是可以瞭解下它的用法)

使用TabHost的Activity需要繼承自TabActivity,且佈局檔案中的id有三個地方需要固定,佈局檔案如下:

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    <span style="color:#ff0000;">android:id="@android:id/tabhost"</span>
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <FrameLayout
            <span style="color:#ff0000;">android:id="@android:id/tabcontent"</span>
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <TabWidget
            <span style="color:#ff0000;">android:id="@android:id/tabs"</span>
            android:background="@drawable/tab_bg"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</TabHost>
注意上面的佈局檔案中標紅的三個地方,這三個地方的id值必須寫成這樣,然後是Activity中的程式碼:
package cn.yubo.testtabhost;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabWidget;

public class TabHostActivity extends TabActivity {
	private TabHost tabHost;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tab_host);
		
		tabHost = getTabHost();
		//新增三個Tab標籤
		tabHost.addTab(tabHost.newTabSpec("tab1")
				.setIndicator("選項1", getResources().getDrawable(R.drawable.tab_activity_normal))
				.setContent(new Intent(this, TabHost1Activity.class)));
		tabHost.addTab(tabHost.newTabSpec("tab2")
				.setIndicator("選項2", getResources().getDrawable(R.drawable.tab_activity_normal))
				.setContent(new Intent(this, TabHost2Activity.class)));
		tabHost.addTab(tabHost.newTabSpec("tab3")
				.setIndicator("選項3", getResources().getDrawable(R.drawable.tab_img_selector))
				.setContent(new Intent(this, TabHost3Activity.class)));
	}
}
在上面的程式碼中,我們首先通過getTabHost()方法得到一個TabHost物件,然後添加了三個導航欄標籤,通過setContent()方法指定了每個標籤跳轉到的頁面,最後的效果圖為:



這裡不知道為什麼在底部的Tab中沒有顯示出圖示來,明明通過setIndicator方法設定了圖示,但是沒顯示出來。

下面說下第二種實現導航欄的方法:

二、使用ViewPager+RadioGroup實現

這種方法實現起來比較容易,就是在頁面上加個ViewPager,底部放一個RadioGroup,裡面放幾個RadioButton起到互斥作用,請看程式碼,首先是佈局檔案:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <RadioGroup
        android:id="@+id/radiogroup"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/tab_bg"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/tab1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:checked="true"
            android:drawableTop="@drawable/tab_img_selector"
            android:gravity="center"
            android:paddingLeft="0dp"
            android:text="選項1" />

        <RadioButton
            android:id="@+id/tab2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:drawableTop="@drawable/tab_img_selector"
            android:gravity="center"
            android:paddingLeft="0dp"
            android:text="選項2" />

        <RadioButton
            android:id="@+id/tab3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:drawableTop="@drawable/tab_img_selector"
            android:gravity="center"
            android:paddingLeft="0dp"
            android:text="選項2" />
    </RadioGroup>

</LinearLayout>
在上面的程式碼中需要注意的一個地方是,在RadioButton裡,我們設定了button屬性為@null,這樣就去掉了原來的RadioButton中的圓圈,但是如果不加paddingLeft="0dp"這個屬性的話,你會發現RadioButton中的圖示和文字還是靠右的,就是說,雖然button屬性設定了@null,但是button佔據的位置還是在的,只有設定了paddingLeft="0dp"和gravity="center"屬性後,RadioButton中的圖示和文字才會居中。

寫完了佈局檔案的程式碼,再來看看Activity中的程式碼該怎麼寫:

package cn.yubo.testtabhost;

import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

/**
 * 使用ViewPager和RadioGroup實現底部導航欄
 * 
 * @author yubo<br/>
 *         2014年12月12日
 */
public class ViewPagerTabActivity extends FinalActivity {
	@ViewInject(id = R.id.viewpager)
	private ViewPager viewPager;
	@ViewInject(id = R.id.radiogroup)
	private RadioGroup radioGroup;
	@ViewInject(id = R.id.tab1)
	private RadioButton tab1;
	@ViewInject(id = R.id.tab2)
	private RadioButton tab2;
	@ViewInject(id = R.id.tab3)
	private RadioButton tab3;

	private List<View> viewList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_pager_tab);

		initViewPager();
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.tab1:
					viewPager.setCurrentItem(0);
					break;
				case R.id.tab2:
					viewPager.setCurrentItem(1);
					break;
				case R.id.tab3:
					viewPager.setCurrentItem(2);
					break;
				}
			}
		});
	}

	private void initViewPager() {
		viewList = new ArrayList<View>();
		viewList.add(LayoutInflater.from(this).inflate(R.layout.page_layout,
				null));
		viewList.add(LayoutInflater.from(this).inflate(R.layout.page_layout,
				null));
		viewList.add(LayoutInflater.from(this).inflate(R.layout.page_layout,
				null));
		viewPager.setAdapter(new MyViewPagerAdapter());
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			public void onPageSelected(int arg0) {
				switch (arg0) {
				case 0:
					tab1.setChecked(true);
					tab2.setChecked(false);
					tab3.setChecked(false);
					break;
				case 1:
					tab1.setChecked(false);
					tab2.setChecked(true);
					tab3.setChecked(false);
					break;
				case 2:
					tab1.setChecked(false);
					tab2.setChecked(false);
					tab3.setChecked(true);
					break;
				}
			}

			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			public void onPageScrollStateChanged(int arg0) {
			}
		});
	}

	private class MyViewPagerAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return viewList.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(viewList.get(position));
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View view = viewList.get(position);
			container.addView(view);
			TextView textView = (TextView) view
					.findViewById(R.id.page_textview);
			textView.setText("第" + position + "頁的資料");
			return view;
		}

	}
}
這裡也沒什麼難點的,就是設定ViewPager滑動時切換RadioButton的選中狀態,然後設定RadioButton被選中時顯示ViewPager的哪個頁面,上面的程式碼中用到了AFinal框架,使用FinalActivity中的註解方式獲取控制元件,其他就沒什麼了,效果圖如下:


三、使用Fragment+RadioButton實現導航欄

這種方式也蠻不錯的,最後實現的效果圖跟第二種方法的一樣,區別之處就在於,第二種方法使用了ViewPager,所以上面的區域是可以左右滑動的,而我們這第三種方式實現的導航欄,上面一部分的區域是不可以左右滑動的,頁面的切換隻能通過下面的導航欄tab來進行,佈局檔案就不上了,跟第二種方法的佈局檔案一致,關鍵是Activity中的程式碼:

package cn.yubo.testtabhost;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class MyFragmentActivity extends FragmentActivity {
	private FragmentManager manager;
	private FragmentTransaction tran;
	private RadioGroup radioGroup;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_my_fragment);
		manager = getSupportFragmentManager();
		tran = manager.beginTransaction();
		tran.replace(R.id.content, new Fragment1());
		tran.commit();
		
		radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				tran = manager.beginTransaction();
				switch(checkedId){
				case R.id.tab1:
					tran.replace(R.id.content, new Fragment1());
					break;
				case R.id.tab2:
					tran.replace(R.id.content, new Fragment2());
					break;
				case R.id.tab3:
					tran.replace(R.id.content, new Fragment3());
					break;
				}
				tran.commit();
			}
		});
	}
}
使用Fragment做這種頁面的切換時,我們要繼承FragmentActivity類,其中比較重要的地方是FragmentManager和FragmentTransaction,通過這兩個類才能實現頁面的切換,下面放上原始碼:

下載原始碼




相關推薦

方式實現Android頁面底部導航

我們在Android手機上使用新浪微博和QQ等一些軟體時,經常會遇到類似下面這種頁面底部導航欄的控制元件,使用這種導航欄可以在手機螢幕的一頁中顯示儘可能多的內容,如下圖所示: 下面我將實現這種導航欄的三種方法總結如下: 一、使用TabHost實現(TabHost在新版的A

Android學習之BottomNavigationBar實現Android特色底部導航

Android底部導航欄的實現方式特別多,例如TabHost,TabLayout,或者TextView等,都可以實現底部導航欄的效果,但是卻沒有Google官方統一的導航欄樣式,今天講的就是Google最近新增到Material design中的底部導航欄Bot

步搞定Android應用底部導航

public class ActivitycollectiondemoActivity extends ActivityCollection {      /** Called when the activity is first created. */      @Override      public

BottomNavigationBar實現Android特色底部導航

Android底部導航欄的實現方式特別多,例如TabHost,TabLayout,或者TextView等,都可以實現底部導航欄的效果,但是卻沒有Google官方統一的導航欄樣式,今天講的就是Google最近新增到Material design中的底部導航欄BottomNa

方式實現自定義圓形頁面載入中效果的進度條,包含一個好看的Android UI

效果圖如下:下載地址 樣式一、通過動畫實現定義res/drawable/loading.xml如下: <?xml version="1.0" encoding="UTF-8"?> ​ <animation-list android:oneshot=

Android 方式實現自定義圓形頁面載入中效果的進度條

一、通過動畫實現定義res/anim/loading.xml如下:<?xml version="1.0" encoding="UTF-8"?>  <animation-list android:oneshot="false"xmlns:android="ht

Android 方式實現圓形ImageView

所有方式均繼承了ImageView 圓形圖片實現一:BitmapShader package com.open.widget; import android.content.Context; import android.graphics.Bitmap; impor

Android進度條】方式實現自定義圓形進度條ProgressBar

總結了3種方法: 1.多張圖片切換 2.自定義顏色 3.旋轉自定義圖片 其它: Android自定義控制元件NumberCircleProgressBar(圓形進度條)的實現:點選開啟連結 橫線帶數字進度條:點選開啟連結

android方式實現自由移動的view

public class MoveView extends ImageView { private int x, y; private int r, l, t, b; public MoveView(Context context) { this(context, n

Android 方式實現三角形氣泡效果、自定義View、shape、點9圖

背景 這期需求中,專案需要這樣一個情況,就是二級選單上面有個三角形 乍一看,用個圖片就可以解決,一個線性佈局、垂直襬下去,所以一開始我是這樣嘗試的,後來發現美工給我切的圖很不合適,不同手機顯示效果也不一樣,所以後來放棄了。以下是解決方案 使用.9圖

詳解Linux搭建vsftp服務器通過方式實現文件傳輸

x86 sys fig passwd 問題: mage vpd cee 啟用 概述 FTP(File Transfer Protocol)中文稱為“文件傳輸協議”。用於Internet上的控制文件的雙向傳輸。 工作原理 一、主動模式: 1、客戶端通過用戶名和密碼登錄服務器

WPFの方式實現快捷鍵

原文: WPFの三種方式實現快捷鍵 最近,對wpf新增快捷鍵的方式進行了整理。主要用到的三種方式如下: 一、wpf命令: 資源中新增命令 <Window.Resources> <RoutedUICommand x:Key="ToolCapClick" Text

實現執行緒的第方式 實現Callable介面

package com.juc; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; /**

方式實現java單例

java的單例模式主要分為:餓漢模式和懶漢模式 餓漢模式:餓漢很飢餓,所以直接先new出來,再提供。 餓漢模式程式碼:載入class檔案的時候就例項化。 package com.jkf.redis; public class HungryManSingleto

方式Android WebView 支援檔案下載

最近在開發的過程中遇到一個需求,那就是讓 WebView 支援檔案下載,比如說下載 apk。WebView 預設是不支援下載的,需要開發者自己實現。既然 PM 提出了需求,那咱就擼起袖子幹唄,於是乎在網上尋找了幾種方法,主要思路有這麼幾種: 跳轉瀏覽器下載 使用系統的下載

Android基礎-底部導航搭建方式二 (RadioGroup+FrameLayout)

程式碼如下:  1.  xml檔案: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/andro

方式實現遠端restful 介面呼叫

1,基本介紹 Restful介面的呼叫,前端一般使用ajax呼叫,後端可以使用的方法比較多,   本次介紹三種:     1.HttpURLConnection實現     2.HttpClient實現     3.Spring的RestTemplate      

以下是JAVA中方式實現檔案字元統計

以下是JAVA中三種方式實現檔案字元統計 package com.lyc.gui; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Ha

方式實現Javaweb頁面跳轉

背景:       自己經手的一個java專案要實現帶參頁面跳轉和頁面跳轉,完成任務後,總結一下自己知道了的幾種方式。 實現:        首先我們有兩大種方式來實現頁面跳轉:1、JS(java

方式實現二維碼(java)

一. 通過使用zxing方式實現:  jar準備: https://github.com/zxing/zxing 下載原始碼,將core/src/main/Java/下的所有檔案和javase/src/main/java/下的所有檔案一起打成jar檔案zxing.jar