`

TabHost 切换带滑动及tab页的数据添加

 
阅读更多

一、在layout下创建TabHost的home.xml

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

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

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

            <LinearLayout
                android:id="@+id/widget_layout_Blue"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" >

                <ListView
                    android:id="@+id/listView"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent" />
            </LinearLayout>

           <LinearLayout
                android:id="@+id/widget_layout_red"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical" >

                <AnalogClock
                    android:id="@+id/widget36"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" >
                </AnalogClock>
               
            </LinearLayout>

            <LinearLayout
                android:id="@+id/widget_layout_green"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical" >

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:text="这是第三个标签页" />

                <RadioGroup
                    android:id="@+id/widget43"
                    android:layout_width="166px"
                    android:layout_height="98px"
                    android:orientation="vertical" >

                    <RadioButton
                        android:id="@+id/widget44"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="RadioButton" >
                    </RadioButton>

                    <RadioButton
                        android:id="@+id/widget45"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="RadioButton" >
                    </RadioButton>
                </RadioGroup>
            </LinearLayout>
        </FrameLayout>
    </LinearLayout>

</TabHost>

二、在layout下创建加载条的footer.xml

<?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="horizontal" >

    <ProgressBar android:id="@+id/c81_forthBar"
        android:layout_width="50dp"
    	android:layout_height="wrap_content"
         style="?android:attr/progressBarStyle" /> 
    <TextView android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:textSize="20sp"
    android:text="数据正在加载..."
    />
</LinearLayout>

 

三、在menu目录下添加menu文件addphone_menu.xml、chatting_menu.xml、phonebook_menu.xml、userapp_menu.xml , 文件内容一致

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
</menu>

四、在drawable目录下添加menu1h.png、menu1n.png和ic_tab_artists.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">    
	<!-- When selected, use grey -->
	<item android:drawable="@drawable/menu1h"
		android:state_selected="true" />    
	<!-- When not selected, use white -->
	<item android:drawable="@drawable/menu1n" />
</selector>

五、在layout目录下创建icon.xml , 用于显示TabHost的图片和文字

<?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" >

	<ImageView
        android:id="@+id/icon"
        android:layout_width="30dip"
        android:layout_height="30dip"
        android:layout_gravity="center"
        android:layout_margin="0dip" />
	
   <TextView
       android:id="@+id/tabsText"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:paddingTop="1dip"
       android:text=""
       android:textSize="12dip" />

</LinearLayout>

 

六、在src目录下HomeActivity.java文件

 

package com.app.activity;

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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.app.R;

@SuppressLint("NewApi")
public class HomeActivity extends Activity {

	private TabHost mTabHost;
	private Menu myMenu;
	private int myMenuSettingTag;
	private ListView listView;
	private int number = 15;// 每次获取多少条数据
	private int maxpage = 5;// 总共有多少页
	private boolean loadfinish = true;
	private View footer;
	private SimpleAdapter adapter;
	private List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
	private static final int myMenuResources[] = { R.menu.phonebook_menu,
			R.menu.addphone_menu, R.menu.chatting_menu, R.menu.userapp_menu };// 将menu添加到数组当中

	private void setupTabHost() {
		// mTabHost = getTabHost();//继承TabActivity使用 , 4.0以后TabActivity过期, 不建议使用
		setContentView(R.layout.home);// 继承Activity使用
		mTabHost = (TabHost) this.findViewById(R.id.tabhost);// 继承Activity使用
		mTabHost.setup();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// construct the tabhost
		setupTabHost();
		mTabHost.setBackgroundColor(Color.argb(150, 22, 70, 150));// 设置tabhost的颜色

		// 继承Activity使用
		TabSpec tabSpec = mTabHost.newTabSpec("one");
		// tabSpec.setIndicator("",
		// getResources().getDrawable(R.drawable.ic_tab_artists));
		tabSpec.setIndicator(createTabView(mTabHost.getContext(), "",
				R.drawable.ic_tab_artists));
		tabSpec.setContent(R.id.widget_layout_Blue);
		mTabHost.addTab(tabSpec);

		tabSpec = mTabHost.newTabSpec("two");
		// tabSpec.setIndicator("",
		// getResources().getDrawable(R.drawable.ic_tab_artists));
		tabSpec.setIndicator(createTabView(mTabHost.getContext(), "",
				R.drawable.ic_tab_artists));
		tabSpec.setContent(R.id.widget_layout_red);
		mTabHost.addTab(tabSpec);

		tabSpec = mTabHost.newTabSpec("three");
		// tabSpec.setIndicator("",
		// getResources().getDrawable(R.drawable.ic_tab_artists));
		tabSpec.setIndicator(createTabView(mTabHost.getContext(), "",
				R.drawable.ic_tab_artists));
		tabSpec.setContent(R.id.widget_layout_green);
		mTabHost.addTab(tabSpec);

		tabSpec = mTabHost.newTabSpec("four");
		// tabSpec.setIndicator("",
		// getResources().getDrawable(R.drawable.ic_tab_artists));
		tabSpec.setIndicator(createTabView(mTabHost.getContext(), "",
				R.drawable.ic_tab_artists));
		tabSpec.setContent(R.id.widget_layout_green);
		mTabHost.addTab(tabSpec);

		/**
		// 继承TabActivity使用
		LayoutInflater.from(this).inflate(R.layout.home,
				mTabHost.getTabContentView(), true);
		mTabHost.addTab(mTabHost.newTabSpec("one")
				// tabid
				.setIndicator("TTT",// tab名称
						getResources().getDrawable(R.drawable.ic_tab_artists))
				.setContent(R.id.widget_layout_Blue));// tab内容
		mTabHost.addTab(mTabHost
				.newTabSpec("two")
				.setIndicator("AAA",
						getResources().getDrawable(R.drawable.ic_tab_artists))
				.setContent(R.id.widget_layout_red));
		mTabHost.addTab(mTabHost
				.newTabSpec("three")
				.setIndicator("BBB",
						getResources().getDrawable(R.drawable.ic_tab_artists))
				.setContent(R.id.widget_layout_green));
		**/
		
		mTabHost.setCurrentTab(0);//默认显示第一个tab,可以不设
		if (mTabHost.getCurrentTab() == 0) {
			show();//默认显示
		}
		mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
				if (tabId.equals("one")) {
					myMenuSettingTag = 1;
				}
				if (tabId.equals("two")) {
					myMenuSettingTag = 2;
				}
				if (tabId.equals("three")) {
					myMenuSettingTag = 3;
				}
				if (tabId.equals("four")) {
					myMenuSettingTag = 4;
				}
				if (myMenu != null) {
					onCreateOptionsMenu(myMenu);
				}

			}

		});
	}

	// 通过MenuInflater过滤器动态加入MENU
	public boolean onCreateOptionsMenu(Menu menu) {
		myMenu = menu;
		myMenu.clear();
		MenuInflater inflater = getMenuInflater();
		switch (myMenuSettingTag) {
		case 1:
			inflater.inflate(myMenuResources[0], menu);
			menu.close();
			break;
		case 2:
			inflater.inflate(myMenuResources[1], menu);
			menu.close();
			break;
		case 3:
			inflater.inflate(myMenuResources[2], menu);
			menu.close();
		default:
			inflater.inflate(myMenuResources[0], menu);
			menu.close();
			break;
		}

		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * 显示列表数据
	 */
	public void show() {
		footer = getLayoutInflater().inflate(R.layout.footer, null);
		listView = (ListView) this.findViewById(R.id.listView);
		listView.setOnScrollListener(new ScrollListener());
		data = load(0, 0);// 第一次加载数据
		adapter = new SimpleAdapter(this, data, R.layout.item, new String[] {
				"name", "phone", "amount" }, new int[] { R.id.name, R.id.phone,
				R.id.amount });
		listView.addFooterView(footer);// 添加页脚(放在ListView最后)
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub

			}

		});
		
		//为ListView添加屏幕的触摸事件 , 如果不加此方法, ListView列表左右滑动无效
		listView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				detector.onTouchEvent(event);
				return onTouchEvent(event);
			}
		});
		listView.removeFooterView(footer);
	}

	private final class ScrollListener implements OnScrollListener {
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			Log.i("MainActivity", "onScrollStateChanged(scrollState="
					+ scrollState + ")");
		}

		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			Log.i("MainActivity", "onScroll(firstVisibleItem="
					+ firstVisibleItem + ",visibleItemCount="
					+ visibleItemCount + ",totalItemCount=" + totalItemCount
					+ ")");

			final int loadtotal = totalItemCount;
			int lastItemid = listView.getLastVisiblePosition();// 获取当前屏幕最后Item的ID
			if ((lastItemid + 1) == totalItemCount) {// 达到数据的最后一条记录
				if (totalItemCount > 0) {
					// 当前页
					int currentpage = totalItemCount % number == 0 ? totalItemCount
							/ number
							: totalItemCount / number + 1;
					int nextpage = currentpage + 1;// 下一页
					if (nextpage <= maxpage && loadfinish) {// 加载完了加载下一页
						loadfinish = false;
						listView.addFooterView(footer);
						new Thread(new Runnable() {
							public void run() {
								try {
									Thread.sleep(1000);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
								List<HashMap<String, Object>> result = load(
										loadtotal, number);
								handler.sendMessage(handler.obtainMessage(100,
										result));
							}
						}).start();
					}
				}

			}
		}

	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			data.addAll((List<HashMap<String, Object>>) msg.obj);
			adapter.notifyDataSetChanged();// 告诉ListView数据已经发生改变,要求ListView更新界面显示
			if (listView.getFooterViewsCount() > 0)
				listView.removeFooterView(footer);
			loadfinish = true;
		}
	};

	/**
	 * 测试数据
	 * 
	 * @param loadtotal
	 * @param number
	 * @return
	 */
	public List<HashMap<String, Object>> load(int loadtotal, int number) {
		List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < 15; i++) {
			HashMap<String, Object> item = new HashMap<String, Object>();
			item.put("name", "xxx");
			item.put("phone", "jjj");
			item.put("amount", "vvv");
			item.put("id", "ooo");
			data.add(item);
		}
		return data;
	}

	/**
	 * 当前页面索引
	 */
	int i = 0;

	/**
	 * 屏幕的触摸事件,如果返回true 则消耗掉这个事件 返回false则未消耗传递下去
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int d = listView.getVisibility();
		Log.i("DDD---", d + "");
		i = mTabHost.getCurrentTab();
		detector.onTouchEvent(event);
		return super.onTouchEvent(event);
	}

	private GestureDetector detector = new GestureDetector(
			new GestureDetector.SimpleOnGestureListener() {
				@Override
				public boolean onFling(MotionEvent e1, MotionEvent e2,
						float velocityX, float velocityY) {
					if ((e2.getRawX() - e1.getRawX()) > 80) {// 滑动的距离

						showNext();// 向右滑动,显示下一个页面
						return true;
					}

					if ((e1.getRawX() - e2.getRawX()) > 80) {
						showPre();// 向左滑动,显示上一个页面
						return true;
					}
					return super.onFling(e1, e2, velocityX, velocityY);
				}

			});

	/**
	 * 显示下一个页面
	 */
	protected void showNext() {
		// 三元表达式控制3个页面的循环.
		mTabHost.setCurrentTab(i = i == 3 ? i = 0 : ++i);
		Log.i("kennet", i + "");
	}

	/**
	 * 显示前一个页面
	 */
	protected void showPre() {
		// 三元表达式控制3个页面的循环.
		mTabHost.setCurrentTab(i = i == 0 ? i = 3 : --i);
	}

	private View createTabView(String name) {
		// View tabView = getLayoutInflater().inflate(R.layout.tab, null);
		LinearLayout linearLayout = new LinearLayout(this);
		linearLayout.setOrientation(LinearLayout.VERTICAL);
		linearLayout.setBackgroundColor(0xFFFFFF);

		TextView textView = new TextView(this);
		textView.setText(name);
		textView.setBackgroundResource(R.drawable.ic_tab_artists);
		textView.setTextColor(0xFFFFFF);
		textView.setTextSize(18.0f);
		textView.setGravity(Gravity.CENTER);
		ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT);
		linearLayout.addView(textView, params);
		return linearLayout;
	}

	private static View createTabView(final Context context, final String text,
			int drawable) {
		View view = LayoutInflater.from(context).inflate(R.layout.icon, null);
		TextView tv = (TextView) view.findViewById(R.id.tabsText);
		tv.setText(text);// 名称
		ImageView iv = (ImageView) view.findViewById(R.id.icon);
		iv.setImageResource(drawable);// 背景图
		return view;
	}
}

 

  • 大小: 35.6 KB
  • 大小: 26.9 KB
  • 大小: 27.3 KB
  • 大小: 2.8 KB
  • 大小: 3.2 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics