Android自定义Tabs文字,背景

public class HomeActivity extends TabActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature ( Window.FEATURE_NO_TITLE );     //去除Title
        setContentView(R.layout.activity_home);
        final TabHost dh =getTabHost(); //获得TabHost实例
        final TabWidget tabWidget = dh.getTabWidget();//获得TabWidget实例
        dh.addTab(dh.newTabSpec("A").setIndicator(getResources().getString(R.string.tab1)).setContent(new Intent(this,FirstActivity.class)));
        dh.addTab(dh.newTabSpec("B").setIndicator(getResources().getString(R.string.tab2)).setContent(new Intent(this,SecondActivity.class)));
        for (int i =0; i < tabWidget.getChildCount(); i++) {
          View child = tabWidget.getChildAt(i);
          final TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title);
          tv.setTextColor(this.getResources().getColorStateList(android.R.color.white));
          tv.setTextSize(10);
          RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tv.getLayoutParams();
          params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0); //取消文字底边对齐
          params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); //设置文字居中对齐
          child.getLayoutParams().height = 30;  
          
              if(dh.getCurrentTab()==i){
                      child.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_selected));
              }
              else {
                      child.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_unselected));
              }
         }  
//设置点击切换背景图        
dh.setOnTabChangedListener(new OnTabChangeListener(){
                public void onTabChanged(String tabId) {
                 // TODO Auto-generated method stub
                 for (int i =0; i < tabWidget.getChildCount(); i++) {
                  View vvv = tabWidget.getChildAt(i);
                  if(dh.getCurrentTab()==i){
                          vvv.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_selected));
                  }
                  else {
                          vvv.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_unselected));
                  }
                 }
                }});
    }

 

posted @ 2012-12-09 14:55  小蚊子子  阅读(250)  评论(0编辑  收藏  举报