標籤:android tabhost tab relativelayout 原始碼
使用TabHost 可以在一個螢幕間進行不同版面的切換,而系統內建的tabhost介面較為樸素,我們應該如何進行自訂修改最佳化呢
MainActivity的原始碼
package com.dream.ledong;import android.app.TabActivity;import android.content.Intent;import android.graphics.Color;import android.os.Bundle;import android.view.Gravity;import android.widget.RelativeLayout;import android.widget.TabHost;import android.widget.TabHost.OnTabChangeListener;import android.widget.TabWidget;import android.widget.TextView;import com.example.client.R;@SuppressWarnings("deprecation")public class itemList extends TabActivity {@Overridepublic void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.itemlist);final TabHost tabHost = getTabHost();Intent remoteIntent = new Intent(itemList.this, item1.class);TabHost.TabSpec remoteTabSpec = tabHost.newTabSpec("remote");remoteTabSpec.setIndicator("運動推薦");remoteTabSpec.setContent(remoteIntent);tabHost.addTab(remoteTabSpec);Intent localIntent = new Intent(itemList.this, item2.class);TabHost.TabSpec localTabSpec = tabHost.newTabSpec("local");localTabSpec.setIndicator("球友人氣");localTabSpec.setContent(localIntent);tabHost.addTab(localTabSpec);Intent localIntent2 = new Intent(itemList.this, item2.class);TabHost.TabSpec localTabSpec2 = tabHost.newTabSpec("a");localTabSpec2.setIndicator("競技氛圍");localTabSpec2.setContent(localIntent2);tabHost.addTab(localTabSpec2); updateTabStyle(tabHost);// 當某個Tab被選中時,則更新背景樣式tabHost.setOnTabChangedListener(new OnTabChangeListener() {@Overridepublic void onTabChanged(String tabId) {updateTabStyle(tabHost);}});}private void updateTabStyle(final TabHost mTabHost) {TabWidget tabWidget = mTabHost.getTabWidget();tabWidget.setRightStripDrawable(R.drawable.list_item_divide_operate);tabWidget.setLeftStripDrawable(R.drawable.list_item_divide_operate);for (int i = 0; i < tabWidget.getChildCount(); i++) {RelativeLayout tabView = (RelativeLayout) mTabHost.getTabWidget().getChildAt(i);TextView text = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title);text.setTextSize(15);RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) text.getLayoutParams();params.width = RelativeLayout.LayoutParams.MATCH_PARENT;params.height = RelativeLayout.LayoutParams.MATCH_PARENT;text.setLayoutParams(params); text.setGravity(Gravity.CENTER);if (mTabHost.getCurrentTab() == i) {// 選中tabView.setBackgroundColor(Color.parseColor("#8DB6CD"));text.setTextColor(this.getResources().getColorStateList(android.R.color.black));} else {// 未選中tabView.setBackgroundColor(Color.parseColor("#ffffff"));text.setTextColor(this.getResources().getColorStateList(android.R.color.darker_gray));}}}}