Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/181.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 向选项卡项添加图标_Android - Fatal编程技术网

Android 向选项卡项添加图标

Android 向选项卡项添加图标,android,Android,在tabsitem中显示图标时遇到问题。它们在xml中显示,但在应用程序运行时不显示 这是xml代码。您可以看到TabItem标签中有android:图标,但它不会出现在应用程序屏幕上 <com.google.android.material.tabs.TabLayout android:id="@+id/tabs" android:layout_width="0dp" android:layout_height="

在tabsitem中显示图标时遇到问题。它们在xml中显示,但在应用程序运行时不显示

这是xml代码。您可以看到TabItem标签中有android:图标,但它不会出现在应用程序屏幕上

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabs"
    android:layout_width="0dp"
    android:layout_height="61dp"
    android:background="@color/colorPrimary"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:tabMode="scrollable"
    app:tabTextColor="@color/colorAccent">

    <com.google.android.material.tabs.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:icon="@drawable/ic_tabicon_principal"
        android:text="Left" />

    <com.google.android.material.tabs.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:icon="@drawable/ic_tabicon_radio"
        android:text="Left2" />


</com.google.android.material.tabs.TabLayout>

好的,您需要在代码中设置图标。有两种方法可以使用
TabLayout

  • 将所有选项卡定义为一个完整的布局,并对所选选项卡之类的事件作出反应
  • 使用适配器并动态创建选项卡
您正在使用第二个选项,这就是为什么您必须提供选项卡标题的原因-适配器正在动态生成选项卡。所以你必须在代码中设置它们,包括图标。从

需要单独对动态创建的选项卡项(如设置图标)进行进一步自定义:


所以,是的,我假设只要在
TabLayout
上设置适配器,您在XML中添加的适配器就会被丢弃。您可以保留它们并使用
OnTabSelectedListener
方法,并使用该方法来控制ViewPager,但显然,只需设置一组图标资源ID并将其应用到现有的内容上就更容易了

如果您将
表格布局的高度设置为
环绕内容
,它会起作用吗?不,它不会起作用。
public class tabsPager extends FragmentStatePagerAdapter {
    
    String [] titles = {"Inicio", "Radio"};

    public tabsPager (FragmentManager fm)
    {
        super(fm);

    }
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {

        return titles[position];
    }


    @Override
    public Fragment getItem(int position) {
        switch (position)
        {
            case 0:
                BlankFragment fragment = new BlankFragment();
                return fragment;
            case 1:
                BlankFragment4 fragment4 = new BlankFragment4();
                return fragment4;
        }
        return null;
    }

    @Override
    public int getCount() {
        return 2;
    }
}
val tab = tabLayout.getTabAt(index)
tab?.icon = drawable