2016-06-28 54 views
-3
import android.support.design.widget.TabLayout; 
import android.support.v4.view.ViewPager; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.support.v7.widget.Toolbar; 
import android.widget.TableLayout; 
import android.widget.TabHost; 

public class MainActivity extends AppCompatActivity { 
    Toolbar toolbar; 
    TabLayout tabLayout; 
    ViewPager viewPager; 
    ViewPagerAdapter viewpagerAdapter; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     toolbar=(Toolbar)findViewById(R.id.toolBar); 
     setSupportActionBar(toolbar); 
     tabLayout=(TabLayout)findViewById(R.id.tabLayout); 
     viewPager=(ViewPager)findViewById(R.id.viewpager); 
     viewpagerAdapter=new ViewPagerAdapter(getSupportFragmentManager()); 
     viewpagerAdapter.addFragments(new HomeFragment(),"Home"); 
     viewpagerAdapter.addFragments(new TopFreeFragment(),"TopFree"); 
     viewpagerAdapter.addFragments(new TopPaidFragment(),"TopPaid"); 
     viewPager.setAdapter(viewpagerAdapter); 
     tabLayout.setupWithViewPager(viewPager); 
     Home.setIndicator("",getResources().getDrawable(R.drawable.iconimage1_design)); 
     TopFree.setIndicator("",getResources().getDrawable(R.drawable.iconimage2_design)); 
     TopPaid.setIndicator("",getResources().getDrawable(R.drawable.iconimage3_design)); 
    } 
} 

在最後3條語句中,紅色的Home,TopFree,TopPaid,shom標誌着我應該提供哪些文本而不是這三個名稱。 任何建議表示讚賞。如何在標籤主機中添加圖標而不是文本

回答

0

您應該得到一個Tab對象並致電setIcon

tabLayout.getTabAt(0).setIcon(R.drawable.iconimage1_design); 
tabLayout.getTabAt(1).setIcon(R.drawable.iconimage2_design); 
tabLayout.getTabAt(2).setIcon(R.drawable.iconimage3_design); 
0

如果你想與您的自定義指標代替文本指示器您可以使用此:

int numTabs = 3; 
int resIds = {R.drawable.image1, R.drawable.image2, R.drawable.image3}; 

for (int i = 0; i < numTabs; i++) { 
    RelativeLayout tab = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.your_custom_sliding_tab_indicator_layout, null); 
    ((ImageView) tab.findViewById(R.id.tab_icon)).setImageResource(resIds[i]); 
    //... 
    //set other values (text, image source etc.) 
    tabLayout.getTabAt(i).setCustomView(tab); 
} 

,或者如果你只需要使用一個圖標,然後使用@胡安的代碼,或修改版本:

int numTabs = 3; 
int resIds = {R.drawable.image1, R.drawable.image2, R.drawable.image3}; 

for (int i = 0; i < numTabs; i++) { 
    tabLayout.getTabAt(i).setIcon(resIds[i]); 
} 
相關問題