Android学习笔记 - TabHost 和 Menu(一)

TabHost


有时,我们想在一个window中显示多个视图,这时就需要用到Tab容器。在Android里它叫TabHost。

使用TabHost有两种方式:

  1. 在相同的activity中使用TabHost导航多个视图
  2. 使用TabHost导航多个Activity(通过intents)
Tab应用的结构
TabHost的Activity的结构如下:
Tabs1.jpg

先看个示例:
layout文件:
[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.   
  3.     <TabHost android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:id="@+id/tabHost"  
  6.     xmlns:android="http://schemas.android.com/apk/res/android"  
  7.     >  
  8.     <TabWidget  
  9.     android:layout_width="fill_parent"  
  10.     android:layout_height="wrap_content"  
  11.     android:id="@android:id/tabs"  
  12.     />  
  13.      <FrameLayout  
  14.      android:layout_width="fill_parent"  
  15.     android:layout_height="fill_parent"  
  16.     android:id="@android:id/tabcontent"  
  17.      >  
  18.      <LinearLayout  
  19.      android:layout_width="fill_parent"  
  20.     android:layout_height="wrap_content"  
  21.     android:id="@+id/tab1"  
  22.     android:orientation="vertical"  
  23.     android:paddingTop="60px"  
  24.      >  
  25.      <TextView    
  26.     android:layout_width="fill_parent"   
  27.     android:layout_height="100px"   
  28.     android:text="This is tab1"  
  29.     android:id="@+id/txt1"  
  30.     />      
  31.       
  32.      </LinearLayout>  
  33.        
  34.      <LinearLayout  
  35.      android:layout_width="fill_parent"  
  36.     android:layout_height="fill_parent"  
  37.     android:id="@+id/tab2"  
  38.     android:orientation="vertical"  
  39.     android:paddingTop="60px"  
  40.      >  
  41.      <TextView    
  42.     android:layout_width="fill_parent"   
  43.     android:layout_height="100px"   
  44.     android:text="This is tab 2"  
  45.     android:id="@+id/txt2"  
  46.     />  
  47.      
  48.      </LinearLayout>  
  49.        
  50.       <LinearLayout  
  51.      android:layout_width="fill_parent"  
  52.     android:layout_height="fill_parent"  
  53.     android:id="@+id/tab3"  
  54.     android:orientation="vertical"  
  55.     android:paddingTop="60px"  
  56.      >  
  57.      <TextView    
  58.     android:layout_width="fill_parent"   
  59.     android:layout_height="100px"   
  60.     android:text="This is tab 3"  
  61.     android:id="@+id/txt3"  
  62.     />  
  63.      
  64.      </LinearLayout>  
  65.      </FrameLayout>  
  66.       
  67.     </TabHost>  

Activity代码:
[java]  view plain copy
  1. public void onCreate(Bundle savedInstanceState) {  
  2. super.onCreate(savedInstanceState);  
  3. setContentView(R.layout.main);  
  4. TabHost tabHost=(TabHost)findViewById(R.id.tabHost);  
  5. tabHost.setup();  
  6.   
  7. TabSpec spec1=tabHost.newTabSpec("Tab 1");  
  8. spec1.setContent(R.id.tab1);  
  9. spec1.setIndicator("Tab 1");  
  10.   
  11. TabSpec spec2=tabHost.newTabSpec("Tab 2");  
  12. spec2.setIndicator("Tab 2");  
  13. spec2.setContent(R.id.tab2);  
  14.   
  15. TabSpec spec3=tabHost.newTabSpec("Tab 3");  
  16. spec3.setIndicator("Tab 3");  
  17. spec3.setContent(R.id.tab3);  
  18.   
  19. tabHost.addTab(spec1);  
  20. tabHost.addTab(spec2);  
  21. tabHost.addTab(spec3);  
  22. }  

  1. 这里通过TabSpecs类创建Tab
  2. 使用setIndicator方法设置tab的文字
  3. 使用setContent设置tab的内容
  4. 如果你使用TabActivity作为你的Activity的基类,你不用调用TabHost.Setup()方法。

运行后看起来是这样的:
Tabs2.jpg

同时还可以指定indicator为一个view:
[java]  view plain copy
  1. TabSpec spec1=tabHost.newTabSpec("Tab 1");  
  2. spec1.setContent(R.id.tab1);  
  3. TextView txt=new TextView(this);  
  4. txt.setText("Tab 1");  
  5. txt.setBackgroundColor(Color.RED);  
  6. spec1.setIndicator(txt);  

设置tab的内容
上面的例子展示了使用tab显示不同的layout资源。如果我们需要通过tab导航到不同的Activity,该怎么办?
这种情况,我们需要有一个activity作为应用的根activity。这个Activity包含TabHost,通过intents导航不同的activity。
注意:根Activity必须继承TabActivity。代码如下:
Layout:
[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <TabHost android:layout_width="fill_parent"  
  3.     android:layout_height="fill_parent"  
  4.     android:id="@android:id/tabhost"  
  5.     xmlns:android="http://schemas.android.com/apk/res/android"  
  6.     >  
  7.     <TabWidget  
  8.     android:layout_width="fill_parent"  
  9.     android:layout_height="wrap_content"  
  10.     android:id="@android:id/tabs"  
  11.     />  
  12.      <FrameLayout  
  13.      android:layout_width="fill_parent"  
  14.     android:layout_height="fill_parent"  
  15.     android:id="@android:id/tabcontent"  
  16.      >  
  17.      </FrameLayout>  
  18.     </TabHost>  

Activity:
[java]  view plain copy
  1. public class TabDemo extends TabActivity {  
  2.     /** Called when the activity is first created. */  
  3.     @Override  
  4.     public void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.main);  
  7.   
  8.         TabHost tabHost=getTabHost();  
  9.         // no need to call TabHost.Setup()          
  10.           
  11.         //First Tab  
  12.         TabSpec spec1=tabHost.newTabSpec("Tab 1");  
  13.         spec1.setIndicator("Tab 1",getResources().getDrawable(R.drawable.sun));  
  14.         Intent in1=new Intent(this, Act1.class);  
  15.         spec1.setContent(in1);  
  16.           
  17.         TabSpec spec2=tabHost.newTabSpec("Tab 2");  
  18.         spec2.setIndicator("Tab 2",getResources().getDrawable(R.drawable.chart));  
  19.         Intent in2=new Intent(this,Act2.class);  
  20.         spec2.setContent(in2);  
  21.   
  22.         tabHost.addTab(spec2);  
  23.         tabHost.addTab(spec3);  
  24.     }  
  25. }  
运行效果

Tabs4.jpg

在运行时添加Tab
在运行时我们可以通过调用TabSepc.setContent(TabContentFactory)方法添加Tab。
[java]  view plain copy
  1. <span style="white-space:pre">  </span>TabSpec spec1=tabHost.newTabSpec("Tab 1");  
  2.         spec1.setIndicator("Tab 1",getResources().getDrawable(R.drawable.sun));  
  3.   
  4.         spec1.setContent(new TabContentFactory() {  
  5.      
  6.   <span style="white-space:pre">        </span> @Override  
  7.   <span style="white-space:pre">        </span> public View createTabContent(String tag) {  
  8.   <span style="white-space:pre">        </span>  // TODO Auto-generated method stub  
  9.       
  10.    <span style="white-space:pre">       </span> return (new AnalogClock(TabDemo.this));  
  11.   <span style="white-space:pre">        </span> }  
  12.  <span style="white-space:pre"> </span> });  

Tabs5.jpg



MENU



菜单是用户界面中最常见的元素之一,使用非常频繁,在Android中,菜单被分为如下三种,选项菜单(OptionsMenu)、上下文菜单(ContextMenu)和子菜单(SubMenu),今天这讲是OptionsMenu 

  一、概述

  public boolean onCreateOptionsMenu(Menu menu):使用此方法调用OptionsMenu 。

  public boolean onOptionsItemSelected(MenuItem item):选中菜单项后发生的动作。

  public void onOptionsMenuClosed(Menu menu):菜单关闭后发生的动作。

  public boolean onPrepareOptionsMenu(Menu menu):选项菜单显示之前onPrepareOptionsMenu方法会被调用,你可以用此方法来根据打当时的情况调整菜单。

  public boolean onMenuOpened(int featureId, Menu menu):单打开后发生的动作。

  二、默认样式

  默认样式是在屏幕底部弹出一个菜单,这个菜单我们就叫他选项菜单OptionsMenu,一般情况下,选项菜单最多显示2排每排3个菜单项,这些菜单项有文字有图标,也被称作Icon Menus,如果多于6项,从第六项开始会被隐藏,在第六项会出现一个More里,点击More才出现第六项以及以后的菜单项,这些菜单项也被称作Expanded Menus。下面介绍。

  

1.main.xml

  2。重载onCreateOptionsMenu(Menu menu)方法

  重载onCreateOptionsMenu(Menu menu)方法,并在此方法中添加菜单项,最后返回true,如果false,菜单则不会显示。

  

public boolean onCreateOptionsMenu(Menu menu)

  3。为菜单项注册事件

  使用onOptionsItemSelected(MenuItem item)方法为菜单项注册事件

public boolean onOptionsItemSelected(MenuItem item)

  4。其他按需要重载

  完整代码

DefaultMenu

5.效果浏览

  

  三、自定义样式

  

1.gridview_menu.xml

   首先自定义菜单界面,我是GridView来包含菜单项,4列3行

  

2.item_menu.xml

菜单项的现实样式,一个图标和一个文字。

  3.定义

  

代码
4.public boolean onMenuOpened(int featureId, Menu menu)

如果第一次打开则设置视图,否则直接显示menuDialog视图。

  

5.private SimpleAdapter getMenuAdapter(String[] menuNameArray,

为菜单添加菜单项。

    
    
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(
" menu " ); // 必须创建一项
return super.onCreateOptionsMenu(menu);
}
复制代码
    
    
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

menuView
= View.inflate( this , R.layout.gridview_menu, null );
// 创建AlertDialog
menuDialog = new AlertDialog.Builder( this ).create();
menuDialog.setView(menuView);
menuDialog.setOnKeyListener(
new OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent
event ) {
if (keyCode == KeyEvent.KEYCODE_MENU) // 监听按键
dialog.dismiss();
return false ;
}
});

menuGrid
= (GridView) menuView.findViewById(R.id.gridview);
menuGrid.setAdapter(getMenuAdapter(menu_name_array, menu_image_array));
/* * 监听menu选项 * */
menuGrid.setOnItemClickListener(
new OnItemClickListener() {
public void onItemClick(AdapterView <?> arg0, View arg1, int arg2,
long arg3) {
switch (arg2) {
case ITEM_SEARCH: // 搜索

break ;
case ITEM_FILE_MANAGER: // 文件管理

break ;
case ITEM_DOWN_MANAGER: // 下载管理

break ;
case ITEM_FULLSCREEN: // 全屏

break ;
case ITEM_MORE: // 翻页
if (isMore) {
menuGrid.setAdapter(getMenuAdapter(menu_name_array2,
menu_image_array2));
isMore
= false ;
}
else { // 首页
menuGrid.setAdapter(getMenuAdapter(menu_name_array,
menu_image_array));
isMore
= true ;
}
menuGrid.invalidate();
// 更新menu
menuGrid.setSelection(ITEM_MORE);
break ;
}


}
});
}
复制代码
复制代码
    
    
package com.wjq.menu;


import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class CustomizeMenu extends Activity {

private boolean isMore = false ; // menu菜单翻页控制
AlertDialog menuDialog; // menu菜单Dialog
GridView menuGrid;
View menuView;

private final int ITEM_SEARCH = 0 ; // 搜索
private final int ITEM_FILE_MANAGER = 1 ; // 文件管理
private final int ITEM_DOWN_MANAGER = 2 ; // 下载管理
private final int ITEM_FULLSCREEN = 3 ; // 全屏
private final int ITEM_MORE = 11 ; // 菜单


/* * 菜单图片 * */
int [] menu_image_array = { R.drawable.menu_search,
R.drawable.menu_filemanager, R.drawable.menu_downmanager,
R.drawable.menu_fullscreen, R.drawable.menu_inputurl,
R.drawable.menu_bookmark, R.drawable.menu_bookmark_sync_import,
R.drawable.menu_sharepage, R.drawable.menu_quit,
R.drawable.menu_nightmode, R.drawable.menu_refresh,
R.drawable.menu_more };
/* * 菜单文字 * */
String[] menu_name_array
= { " 搜索 " , " 文件管理 " , " 下载管理 " , " 全屏 " , " 网址 " , " 书签 " ,
" 加入书签 " , " 分享页面 " , " 退出 " , " 夜间模式 " , " 刷新 " , " 更多 " };
/* * 菜单图片2 * */
int [] menu_image_array2 = { R.drawable.menu_auto_landscape,
R.drawable.menu_penselectmodel, R.drawable.menu_page_attr,
R.drawable.menu_novel_mode, R.drawable.menu_page_updown,
R.drawable.menu_checkupdate, R.drawable.menu_checknet,
R.drawable.menu_refreshtimer, R.drawable.menu_syssettings,
R.drawable.menu_help, R.drawable.menu_about, R.drawable.menu_return };
/* * 菜单文字2 * */
String[] menu_name_array2
= { " 自动横屏 " , " 笔选模式 " , " 阅读模式 " , " 浏览模式 " , " 快捷翻页 " ,
" 检查更新 " , " 检查网络 " , " 定时刷新 " , " 设置 " , " 帮助 " , " 关于 " , " 返回 " };
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

menuView
= View.inflate( this , R.layout.gridview_menu, null );
// 创建AlertDialog
menuDialog = new AlertDialog.Builder( this ).create();
menuDialog.setView(menuView);
menuDialog.setOnKeyListener(
new OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent
event ) {
if (keyCode == KeyEvent.KEYCODE_MENU) // 监听按键
dialog.dismiss();
return false ;
}
});

menuGrid
= (GridView) menuView.findViewById(R.id.gridview);
menuGrid.setAdapter(getMenuAdapter(menu_name_array, menu_image_array));
/* * 监听menu选项 * */
menuGrid.setOnItemClickListener(
new OnItemClickListener() {
public void onItemClick(AdapterView <?> arg0, View arg1, int arg2,
long arg3) {
switch (arg2) {
case ITEM_SEARCH: // 搜索

break ;
case ITEM_FILE_MANAGER: // 文件管理

break ;
case ITEM_DOWN_MANAGER: // 下载管理

break ;
case ITEM_FULLSCREEN: // 全屏

break ;
case ITEM_MORE: // 翻页
if (isMore) {
menuGrid.setAdapter(getMenuAdapter(menu_name_array2,
menu_image_array2));
isMore
= false ;
}
else { // 首页
menuGrid.setAdapter(getMenuAdapter(menu_name_array,
menu_image_array));
isMore
= true ;
}
menuGrid.invalidate();
// 更新menu
menuGrid.setSelection(ITEM_MORE);
break ;
}


}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(
" menu " ); // 必须创建一项
return super.onCreateOptionsMenu(menu);
}

private SimpleAdapter getMenuAdapter(String[] menuNameArray,
int [] imageResourceArray) {
ArrayList
< HashMap < String, Object >> data = new ArrayList < HashMap < String, Object >> ();
for ( int i = 0 ; i < menuNameArray.length; i ++ ) {
HashMap
< String, Object > map = new HashMap < String, Object > ();
map.put(
" itemImage " , imageResourceArray[i]);
map.put(
" itemText " , menuNameArray[i]);
data.add(map);
}
SimpleAdapter simperAdapter
= new SimpleAdapter( this , data,
R.layout.item_menu,
new String[] { " itemImage " , " itemText " },
new int [] { R.id.item_image, R.id.item_text });
return simperAdapter;
}
@Override
public boolean onMenuOpened( int featureId, Menu menu) {
if (menuDialog == null ) {
menuDialog
= new AlertDialog.Builder( this ).setView(menuView).show();
}
else {
menuDialog.show();
}
return false ; // 返回为true 则显示系统menu
}

}
复制代码

原代码下载点击这里

效果浏览

          




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值