选中和取消选中时,Android更改选项卡栏文本颜色

时间:2014-06-23 12:41:36

标签: android android-tabhost android-tabs

我如何更改android标签中的文字颜色,任何人都可以帮助我:

选择标签时,文字颜色为红色,因为您可以看到图像:

enter image description here

当取消选中标签时,文字将为白色,如图中所示:

enter image description here

这是我的Tab_Car_Shop.java类:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    final TabHost mTabHost = getTabHost();
    createHomeTab(mTabHost);
//  createContactTab(mTabHost);
    createnotificationTab(mTabHost);
//  createEmergencyTab(mTabHost);
    createFavouritesTab(mTabHost);
//  createMoreTab(mTabHost);
    createProfileTab(mTabHost);

//      DealerEmergencyNumbers = getIntent().getExtras().getString("DealerEmergencyNumbers");


//       csHeader_logo = getIntent().getExtras().getString("csHeader_logo");




     getTabHost().setOnTabChangedListener(new OnTabChangeListener() {


        @Override
           public void onTabChanged(String tabId)
           {

               if (getTabHost().getCurrentTabTag().equals("tab_contact"))
               { 
                   UpdateList();

                   if(csSavedDealerID == null)
                       showMessage("To benefit from the full features of this app please fill in your profile.");
                   else
                       showCutomMessage("Would you like to call for emergency assistance"); 
                   final TabHost mTabHost = getTabHost();
                   mTabHost.setCurrentTab(tabClick);

               }
               tabClick = getTabHost().getCurrentTab();


             }
           });



}



public void switchTab(int tab)
 {
    getTabHost().setCurrentTab(tab);
}

public void createHomeTab(TabHost mTabHost)
{
    // Create Intent for My Info



    Intent intent_settings = new Intent(Tab_Car_Shop.this,Car_shop_group_activity.class);
    //intent_settings.putExtras(CarData);

    intent_settings.putExtra("csDealerID", csDealerID);
    intent_settings.putExtra("csMakeID","-1");
    intent_settings.putExtra("csMakeName","Carshop");
    intent_settings.putExtra("csImageUrl", "http://cmh.dealer-app.co.za/cmh_v1/images/home-cons/logo-carshop.png");
    intent_settings.putExtra("csHeader_logo", "http://cmh.dealer-app.co.za/cmh_v1/images/headers/carshop-header.png");
    intent_settings.putExtra("csAdvert","http://cmh.dealer-app.co.za/cmh_v1/images/advert/advert-carshop.gif");
    intent_settings.putExtra("UsedVehicleLabel","Carshop");
    intent_settings.putExtra("bCarShop", true);
    intent_settings.putExtra("DealerEmergencyNumbers","");


//  startActivity(intent_settings);

    // mTabHost.addTab(mTabHost.newTabSpec("tab_my_info").setIndicator(language.txt_myinfo[language.language], getResources().getDrawable(R.drawable.tab_my_info)).setContent(intent_my_info));

     TabHost.TabSpec spec = mTabHost.newTabSpec("tab_home");        

        View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_layout, getTabWidget(), false);

        TextView title = (TextView) tabIndicator.findViewById(R.id.tab_title);
        title.setText("Home");
        // for Home text will be red
    //  title.setTextColor(Color.parseColor("#FF0000"));
        ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
        icon.setImageResource(R.drawable.tab_home);

        spec.setIndicator(tabIndicator);
        spec.setContent(intent_settings);
        mTabHost.addTab(spec);


        int height = mTabHost.getTabWidget().getChildAt(0).getLayoutParams().height;

        //Log.e("CMH", "tab Hight " + height);
}


//  public void createContactTab(TabHost mTabHost)
public void createnotificationTab(TabHost mTabHost)
{
    // Create Intent for My Info

    Intent intent_settings = new Intent(Tab_Car_Shop.this,
            Promotions.class);

    intent_settings.putExtra("bCarShop", true);
    intent_settings.putExtra("csHeader_logo", "http://cmh.dealer-app.co.za/cmh_v1/images/headers/carshop-header.png");
    // mTabHost.addTab(mTabHost.newTabSpec("tab_my_info").setIndicator(language.txt_myinfo[language.language], getResources().getDrawable(R.drawable.tab_my_info)).setContent(intent_my_info));

     TabHost.TabSpec spec = mTabHost.newTabSpec("tab_notifications");       

        View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_layout, getTabWidget(), false);

        TextView title = (TextView) tabIndicator.findViewById(R.id.tab_title);
        title.setText("Notifications");
        ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
        icon.setImageResource(R.drawable.tab_contact);

        spec.setIndicator(tabIndicator);
        spec.setContent(intent_settings);
        mTabHost.addTab(spec);
}

//  public void createEmergencyTab(TabHost mTabHost)
public void createFavouritesTab(TabHost mTabHost)
{
    // Create Intent for My Info


    Intent intent_settings = new Intent(Tab_Car_Shop.this,
            Favourities.class);

    intent_settings.putExtra("bCarShop", true);
    intent_settings.putExtra("csHeader_logo", "http://cmh.dealer-app.co.za/cmh_v1/images/headers/carshop-header.png");
    intent_settings.putExtra("Previous_Activity", "More_group_activity");
    // mTabHost.addTab(mTabHost.newTabSpec("tab_my_info").setIndicator(language.txt_myinfo[language.language], getResources().getDrawable(R.drawable.tab_my_info)).setContent(intent_my_info));

     TabHost.TabSpec spec = mTabHost.newTabSpec("tab_favourites");      

        View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_layout, getTabWidget(), false);

        TextView title = (TextView) tabIndicator.findViewById(R.id.tab_title);
        title.setText("My favourites");
        ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
        icon.setImageResource(R.drawable.tab_favourites);

        spec.setIndicator(tabIndicator);
        spec.setContent(intent_settings);
        mTabHost.addTab(spec);


}


//  public void createMoreTab(TabHost mTabHost)
public void createProfileTab(TabHost mTabHost)
{
    // Create Intent for My Info

    Intent intent_settings = new Intent(Tab_Car_Shop.this,
            MyProfile.class);

    intent_settings.putExtra("bCarShop", true);
    intent_settings.putExtra("csHeader_logo", "http://cmh.dealer- app.co.za/cmh_v1/images/headers/carshop-header.png");
    intent_settings.putExtra("Previous_Activity", "More_group_activity");
    // mTabHost.addTab(mTabHost.newTabSpec("tab_my_info").setIndicator(language.txt_myinfo[language.language], getResources().getDrawable(R.drawable.tab_my_info)).setContent(intent_my_info));

     TabHost.TabSpec spec = mTabHost.newTabSpec("tab_profile");     

        View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_layout, getTabWidget(), false);

        TextView title = (TextView) tabIndicator.findViewById(R.id.tab_title);
        title.setText("My profile");
        ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
        icon.setImageResource(R.drawable.tab_profile);

        spec.setIndicator(tabIndicator);
        spec.setContent(intent_settings);
        mTabHost.addTab(spec);



}

 public void showCutomMessage(String message)
    {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setMessage(message).setCancelable(true).setPositiveButton(
                "Yes", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {

                        dialog.cancel();


                        if(csEmergencyNumber.length() <= 0 && emergencyNumberList.size() <= 0)
                        {
                            showMessage("No Emergency Number found.");
                         }
                         else if (csEmergencyNumber.length() > 0)
                         {
                             String url = "tel:" + csEmergencyNumber;
                             Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
                             startActivity(intent);
                         }
                         else
                         {
                             if (emergencyNumberList.size() == 1)
                             {
                                 String url = "tel:" + emergencyNumberList.get(0);
                                 Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
                                  startActivity(intent);
                             }
                             else
                             {
                                 showEmergencyNumberDialog();
                             }
                         }
                    }
                }).setNegativeButton(
                        "No", new DialogInterface.OnClickListener()
                        {
                            public void  onClick(DialogInterface dialog, int id)
                            {

                                dialog.cancel();

                            }
                        });


        AlertDialog alert = builder.create();
        alert.setMessage(message);


        alert.show();

    }

 public void showMessage(String message)
    {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setMessage(message).setCancelable(true).setPositiveButton(
                "OK", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {

                        dialog.cancel();
                    }
                });


        AlertDialog alert = builder.create();
        alert.setMessage(message);


        alert.show();

    }

 public void UpdateList()
 {
     try
        {
            emergencyNumberList.clear();
            jsonNumberArray = new  JSONArray(DealerEmergencyNumbers.toString());

            SharedPreferences app_preferences =  PreferenceManager.getDefaultSharedPreferences(Tab_Car_Shop.this);
            csSavedDealerID = app_preferences.getString("DealerID", null);

            for(int nJasonIndex = 0; nJasonIndex < jsonNumberArray.length(); nJasonIndex++)
            {
                JSONObject emergencyObj =jsonNumberArray.getJSONObject(nJasonIndex);
                String csNumber = emergencyObj.getString("EmergencyNumber");
                String csNumber2 = emergencyObj.getString("office_hours_num"); 
                /*Log.e("Usman String1", csNumber);
                Log.e("Usman String2", csNumber2);*/
                String csMakeDealerID = emergencyObj.getString("DealerID");
                if(csSavedDealerID != null && csSavedDealerID.equalsIgnoreCase(csMakeDealerID))
                {
                    csEmergencyNumber = csNumber;
                }
                else
                {
                    if(!csNumber.equals(""))
                        emergencyNumberList.add("After Hours: " + csNumber);
                    if(!csNumber2.equals(""))
                        emergencyNumberList.add("Office Hours: " + csNumber2); 
                }

            }

            if(emergencyNumberList.size() > 1)
            {
                myEmergencyAdapter =new ArrayAdapter<String> (this,android.R.layout.simple_spinner_item,emergencyNumberList); 
                 myEmergencyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            }




        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 }

 void showEmergencyNumberDialog()
 {
     ArrayAdapter adapter = new  ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item, emergencyNumberList);

     AlertDialog.Builder builder = new AlertDialog.Builder(this);
     builder.setTitle("");
     builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int item)
         {
             if (item >= 0)
             {
                 String emergencyNumber = emergencyNumberList.get(item);
                 String[] parts = emergencyNumber.split(": ");
                 String number = parts[1]; // 034556
                 String url = "tel:" + number; 
                 Intent intent = new Intent(Intent.ACTION_CALL,  Uri.parse(url));
                 startActivity(intent);
             }

         }
     });

     AlertDialog alert = builder.create();
     alert.show();
 }


}

这是我的tab_layout.xml文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabhost"
android:layout_width="0dip"
android:layout_height="50dp"
android:layout_weight="1"
android:background="@drawable/tab_indicator"
android:orientation="vertical"
android:padding="5dp" >

<ImageView
    android:id="@+id/icon"
    android:layout_width="25dp"
    android:layout_height="25dp"
    android:layout_centerHorizontal="true" />

<TextView
    android:id="@+id/tab_title"
    style="?android:attr/tabWidgetStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:textSize="12sp" />

</RelativeLayout>

这是我的tab_home.xml文件:

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

</item>
<!-- When not selected, use that-->
<item android:drawable="@drawable/img_home_new"
    android:state_selected="false" />
</selector>

这是我的tab_indicator.xml文件:

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

<!-- Pressed -->
<item android:state_selected="true" android:state_pressed="true"  android:drawable="@drawable/img_bottombar_new" />
 <item android:state_selected="true" android:state_pressed="false"  android:drawable="@drawable/img_bottombar_new" />
<!--<item android:state_pressed="true" android:drawable="@drawable/bottom_bar_selected"  />-->
</selector>

2 个答案:

答案 0 :(得分:4)

public void onTabChanged(String tabId) {
    // TODO Auto-generated method stub
    for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
    {
        View view = mTabHost.getTabWidget().getChildTabViewAt(i);
        if ( view != null ) {

            // get title text view
            TextView textView = (TextView)view. findViewById(R.id.tab_title);
            textView.setTextColor(Color.WHITE);
        }

    }
    title.setTextColor(Color.RED); 
}

答案 1 :(得分:3)

试试这个

tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener(){
    @Override
    public void onTabChanged(String id) {
        int tab = tabHost.getCurrentTab();
        View v = tabHost.getTabWidget().getChildAt(tab).setBackgroundColor(Color.RED);
    }
});

您还可以查看this帖子是否有帮助。

其他替代方案是Actionbar Style generator。您可以指定您的要求,下载zip并在项目中使用。

要更改文字颜色,您可以尝试一下:

TextView tv = (TextView) tabWidget.getChildAt(i).findViewById(android.R.id.title);        
tv.setTextColor(Color.RED);

编辑:

您可以使用此逻辑,以便在取消选择标签栏时将颜色更改为白色。

public void onTabChanged(String tabId) {
    // TODO Auto-generated method stub
    for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
    {
        View view = mTabHost.getTabWidget().getChildTabViewAt(i);
        if ( view != null ) {

            // get title text view
            TextView textView = (TextView) findViewById(R.id.tab_title);
            textView.setTextColor(Color.WHITE);
        }

    }
    title.setTextColor(Color.RED); 
}

希望这有帮助。