2012-06-12 2 views
2
 TabHost tabHost = getTabHost(); // The activity TabHost 
    TabHost.TabSpec spec; // Resusable TabSpec for each tab 
    Intent intent; // Reusable Intent for each tab 

    // Create an Intent to launch an Activity for the tab (to be reused) 
    intent = new Intent().setClass(this, NewUserActivity.class); 

    // Initialize a TabSpec for each tab and add it to the TabHost 
    Display display = getWindowManager().getDefaultDisplay(); 
    int width = display.getWidth(); 

    spec = tabHost.newTabSpec("New User").setIndicator("New User").setContent(intent); 
    tabHost.addTab(spec); 

    // Do the same for the other tabs 
    intent = new Intent().setClass(this, ExistingUserActivity.class); 
    spec = tabHost.newTabSpec("Existing User").setIndicator("Existing User").setContent(intent); 
    tabHost.addTab(spec); 

    tabHost.getTabWidget() 
      .getChildAt(0) 
      .setLayoutParams(
        new LinearLayout.LayoutParams((width/2) - 2, 40)); 
    tabHost.getTabWidget() 
      .getChildAt(1) 
      .setLayoutParams(
        new LinearLayout.LayoutParams((width/2) - 2, 40)); 
    TabWidget tw = getTabWidget(); 

    tw.getChildAt(0).setBackgroundColor(Color.parseColor("#800000")); 
    tw.getChildAt(1).setBackgroundColor(Color.parseColor("#FF6347")); 

} 

@Override 
public void onTabChanged(String x) { 

} 

Приведенный выше код инициализирует TabHost. Он использует две вкладки. Один - новый пользователь и другой - существующий пользователь. При нажатии любой из них я хочу, чтобы вкладка была сфокусирована и отличалась цветом, чем другая. Я не знаю, как использовать метод OnTabChanged.Как использовать метод OnTabChanged в android?

ответ

4

При нажатии любой из них, я хочу, чтобы вкладка была сфокусирована, а - другой цвет, чем другой.

Вы можете реализовать его следующим образом.

tabHost.setOnTabChangedListener(new OnTabChangeListener() { 

      public void onTabChanged(String str) { 
       tabHost.getCurrentTabView().setBackgroundColor(color); 
       tabHost.getCurrentTabView().setBackgroundDrawable(drawable); 
       tabHost.getCurrentTabView().setBackgroundResource(resid); 
      } 
     }); 
0

Для вкладок настройки с различными состояниями, создают эти два метода:

private void setupTab(final View view, final String tag, Intent intent) { 
    View tabview = createTabView(tabHost.getContext(), tag); 
    TabSpec tabSpec = tabHost.newTabSpec(tag).setIndicator(tabview).setContent(intent); 
    tabHost.addTab(tabSpec); 
} 

private static View createTabView(final Context context, final String text) { 
    View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null); 
    TextView tv = (TextView) view.findViewById(R.id.tabsText);  
    tv.setText(text); 
    tv.setTypeface(tf); 
    return view; 
} 

Затем создать tabs_bg.xml в папке макета:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/tabsLayout" android:layout_width="fill_parent" 
android:layout_height="fill_parent" android:background="@drawable/tab_bg_selector" 
android:padding="10dip" android:gravity="center" android:orientation="vertical"> 
    <TextView android:id="@+id/tabsText" android:layout_width="wrap_content" 
     android:layout_height="wrap_content" android:text="Title" 
     android:textSize="15dip" android:textColor="@drawable/tab_text_selector" /> 
</LinearLayout> 

Теперь в вытяжке папку, создать XML-файл файлы. tab_bg_selector.xml, tab_bg_selected.xml и tab_bg_unselected.xml:

--- TAB ВЫБОРА ---

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<!-- Active tab --> 
<item android:state_selected="true" android:state_focused="false" 
    android:state_pressed="false" android:drawable="@drawable/tab_bg_selected" /> 
<!-- Inactive tab --> 
<item android:state_selected="false" android:state_focused="false" 
    android:state_pressed="false" android:drawable="@drawable/tab_bg_unselected" /> 
<!-- Pressed tab --> 
<item android:state_pressed="true" android:drawable="@drawable/tab_bg_selected" /> 
<!-- Selected tab (using d-pad) --> 
<item android:state_focused="true" android:state_selected="true" 
    android:state_pressed="false" android:drawable="@drawable/tab_bg_selected" /> 
</selector> 

--- TAB SELECED ---

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="rectangle"> 
<gradient android:startColor="#A8A8A8" android:centerColor="#7F7F7F" 
    android:endColor="#696969" android:angle="-90" /> 
</shape> 

--- TAB UNSELECTED ---

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="rectangle"> 
<gradient android:startColor="#5C5C5C" android:centerColor="#424242" 
    android:endColor="#222222" android:angle="-90" /> 
</shape> 

И установите цвета в любое удобное для вас место, удачи! О, я чуть не забыл, а также при установке Intent в tabhost, используйте метод setupTab так:

Intent i = new Intent(this, AAACalendarActivity.class); 
    setupTab(new TextView(this), "Month", i); 
    i = new Intent(this, AAACalendarWeekActivity.class); 
    setupTab(new TextView(this), "Week", i); 
    i = new Intent(this, AAACalendarDayActivity.class); 
    setupTab(new TextView(this), "Day", i); 
+0

Постараюсь сделать это. Большое спасибо! – Chetna

+0

Это хороший способ реализации ваших вкладок, и вы можете использовать его для всех своих TabActivities. – Carnal

+1

Это сработало ...? – Carnal

Смежные вопросы