TabWidget实现不同Activity的切换

效果图:



核心代码:

public class tabUtils {
	static int sActiveTabIndex = -1;
  static boolean updateTabState(Activity a,int hightlight){
	  boolean isActive=false;
	  final TabWidget tw=(TabWidget) a.findViewById(R.id.widgetbus);
	  for(int i=0;i<tw.getChildCount();i++){
		  View v=tw.getChildAt(i);
		  if(v.getId()==hightlight)
		  {
			  isActive=true;
			  tw.setCurrentTab(i);	
			  sActiveTabIndex=i;
		  }
		  v.setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				processtabclick((Activity)tw.getContext(),v,tw.getChildAt(sActiveTabIndex).getId());
			}			  
		  });
		  v.setOnFocusChangeListener( new View.OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if(hasFocus){
					for(int i=0;i<tw.getChildCount();i++){
						if(v==tw.getChildTabViewAt(i))
							tw.setCurrentTab(i);
						processtabclick((Activity)tw.getContext(),v,tw.getChildAt(sActiveTabIndex).getId());
						break;
					}
				}
			}
		});
	  }
	  return true;
  }
  static void processtabclick(Activity a,View v,int curent){
	  int id=v.getId();
	  if(v.getId()==curent)
	  {
		  return;
	  }
	  activetab(a,id);
	  
  }
  static void activetab(Activity a,int id){
	  Intent intent=new Intent();
	  switch(id)
	  {
	  case R.id.text1:
		  intent.setClass(a, TabWidgteTest.class);
		  break;
	  case R.id.text2:
		  intent.setClass(a, activity2.class);
		  break;
	  case R.id.text3:
		  intent.setClass(a, activity3.class);
		  break;
	  case R.id.text4:
		  intent.setClass(a, activity4.class);
		  break;
	  default:
		  return;
	  }
		  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		  a.startActivity(intent);
		  a.finish();
		  a.overridePendingTransition(0, 0);
	  }
}

原理分析:在TabWidget中加入四个TextView,在每个TextView上绑定OnClickListener监听器,

当有OnClick事件时,会判断点击的View是否是focus的,如果不是则启动点击的item所代表的activity。

源码下载地址:http://download.csdn.net/detail/txj8612/5264944

你可能感兴趣的:(android,tabwidget)