📌  相关文章
📜  如何在 Android 中实现带有图标的 TabLayout?

📅  最后修改于: 2022-05-13 01:54:37.658000             🧑  作者: Mango

如何在 Android 中实现带有图标的 TabLayout?

TabLayout 用于实现水平选项卡。设计支持库中引入了 TabLayout 来实现选项卡。选项卡是使用 TabLayout 类的 newTab() 方法创建的。选项卡的标题和图标分别通过 TabListener 接口的 setText(int) 和 setIcon(int) 方法设置。使用方法 addTab(Tab) 方法将布局选项卡附加到 TabLayout 上。

我们将在本文中构建什么?

在本文中,我们将在 viewPager 的帮助下制作三个带有各自图标的单独选项卡。下面显示了我们将在本文中构建的示例视频。请注意,我们将用Java语言实现这个项目。

分步实施

步骤 1:创建一个新项目

  • 打开一个新项目。
  • 我们将使用Java语言开发 Empty Activity。保持所有其他选项不变。
  • 您可以在方便时更改项目的名称。
  • 将有两个名为 activity_main.xml 和 MainActivity 的默认文件。Java

如果您不知道如何在 Android Studio 中创建新项目,可以参考如何在 Android Studio 中创建/启动新项目?

第 2 步:添加所需的依赖项

导航到 Gradle 脚本 > build.gradle(module) 和其中的以下依赖项-

implementation 'com.google.android.material:material:1.2.1'

第 3 步:处理 XML 文件

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件。下面是activity_main.xml文件的代码。

XML


 
    
   
    
 


XML


 
   
 


Java
package com.example.tablayoutwithicon;
 
import androidx.annotation.ContentView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
 
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
 
import com.google.android.material.tabs.TabLayout;
 
import java.lang.reflect.Array;
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity {
 
    // Initialize variables
    TabLayout tabLayout;
    ViewPager viewPager;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // assign variable
        tabLayout=findViewById(R.id.tab_layout);
        viewPager=findViewById(R.id.view_pager);
 
        // Initialize array list
        ArrayList arrayList=new ArrayList<>(0);
 
        // Add title in array list
        arrayList.add("Basic");
        arrayList.add("Advance");
        arrayList.add("Pro");
 
        // Setup tab layout
        tabLayout.setupWithViewPager(viewPager);
 
        // Prepare view pager
        prepareViewPager(viewPager,arrayList);
          
    }
 
    private void prepareViewPager(ViewPager viewPager, ArrayList arrayList) {
        // Initialize main adapter
        MainAdapter adapter=new MainAdapter(getSupportFragmentManager());
         
        // Initialize main fragment
        MainFragment mainFragment=new MainFragment();
         
        // Use for loop
        for(int i=0;i fragmentArrayList= new ArrayList<>();
        ArrayList stringArrayList=new ArrayList<>();
 
        int[] imageList={R.drawable.basic,R.drawable.advance,R.drawable.pro};
 
        // Create constructor
        public void addFragment(Fragment fragment,String s)
        {
            // Add fragment
            fragmentArrayList.add(fragment);
            // Add title
            stringArrayList.add(s);
        }
 
        public MainAdapter(FragmentManager supportFragmentManager) {
            super(supportFragmentManager);
        }
 
        @NonNull
        @Override
        public Fragment getItem(int position) {
            // return fragment position
            return fragmentArrayList.get(position);
        }
 
        @Override
        public int getCount() {
            // Return fragment array list size
            return fragmentArrayList.size();
        }
 
        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
 
            // Initialize drawable
            Drawable drawable= ContextCompat.getDrawable(getApplicationContext()
            ,imageList[position]);
 
            // set bound
            drawable.setBounds(0,0,drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
 
            // Initialize spannable image
            SpannableString spannableString=new SpannableString(""+stringArrayList.get(position));
 
            // Initialize image span
            ImageSpan imageSpan=new ImageSpan(drawable,ImageSpan.ALIGN_BOTTOM);
 
            // Set span
            spannableString.setSpan(imageSpan,0,1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
 
            // return spannable string
            return spannableString;
        }
    }
}


Java
package com.example.tablayoutwithicon;
 
import android.os.Bundle;
 
import androidx.fragment.app.Fragment;
 
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
 
public class MainFragment extends Fragment {
    // Initialize variable
    TextView textView;
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Initialize view
        View view =inflater.inflate(R.layout.fragment_main, container, false);
 
        // Assign variable
        textView=view.findViewById(R.id.text_view);
 
        // Get Title
        String sTitle=getArguments().getString("title");
         
        // Set title on text view
        textView.setText(sTitle);
 
        // return view
        return view;
    }
}



导航到应用 > 右键单击 > 新建 > 片段 > 空白片段。将片段命名为 MainFragment。下面是fragment_main.xml文件的代码 -

XML



 
   
 


第 4 步:处理Java文件

转到 MainActivity。 Java文件并参考以下代码。下面是MainActivity 的代码。 Java文件。

Java

package com.example.tablayoutwithicon;
 
import androidx.annotation.ContentView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
 
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
 
import com.google.android.material.tabs.TabLayout;
 
import java.lang.reflect.Array;
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity {
 
    // Initialize variables
    TabLayout tabLayout;
    ViewPager viewPager;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // assign variable
        tabLayout=findViewById(R.id.tab_layout);
        viewPager=findViewById(R.id.view_pager);
 
        // Initialize array list
        ArrayList arrayList=new ArrayList<>(0);
 
        // Add title in array list
        arrayList.add("Basic");
        arrayList.add("Advance");
        arrayList.add("Pro");
 
        // Setup tab layout
        tabLayout.setupWithViewPager(viewPager);
 
        // Prepare view pager
        prepareViewPager(viewPager,arrayList);
          
    }
 
    private void prepareViewPager(ViewPager viewPager, ArrayList arrayList) {
        // Initialize main adapter
        MainAdapter adapter=new MainAdapter(getSupportFragmentManager());
         
        // Initialize main fragment
        MainFragment mainFragment=new MainFragment();
         
        // Use for loop
        for(int i=0;i fragmentArrayList= new ArrayList<>();
        ArrayList stringArrayList=new ArrayList<>();
 
        int[] imageList={R.drawable.basic,R.drawable.advance,R.drawable.pro};
 
        // Create constructor
        public void addFragment(Fragment fragment,String s)
        {
            // Add fragment
            fragmentArrayList.add(fragment);
            // Add title
            stringArrayList.add(s);
        }
 
        public MainAdapter(FragmentManager supportFragmentManager) {
            super(supportFragmentManager);
        }
 
        @NonNull
        @Override
        public Fragment getItem(int position) {
            // return fragment position
            return fragmentArrayList.get(position);
        }
 
        @Override
        public int getCount() {
            // Return fragment array list size
            return fragmentArrayList.size();
        }
 
        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
 
            // Initialize drawable
            Drawable drawable= ContextCompat.getDrawable(getApplicationContext()
            ,imageList[position]);
 
            // set bound
            drawable.setBounds(0,0,drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
 
            // Initialize spannable image
            SpannableString spannableString=new SpannableString(""+stringArrayList.get(position));
 
            // Initialize image span
            ImageSpan imageSpan=new ImageSpan(drawable,ImageSpan.ALIGN_BOTTOM);
 
            // Set span
            spannableString.setSpan(imageSpan,0,1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
 
            // return spannable string
            return spannableString;
        }
    }
}


转到 MainFragment。 Java文件并参考以下代码。下面是MainFragment 的代码。 Java文件。

Java

package com.example.tablayoutwithicon;
 
import android.os.Bundle;
 
import androidx.fragment.app.Fragment;
 
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
 
public class MainFragment extends Fragment {
    // Initialize variable
    TextView textView;
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Initialize view
        View view =inflater.inflate(R.layout.fragment_main, container, false);
 
        // Assign variable
        textView=view.findViewById(R.id.text_view);
 
        // Get Title
        String sTitle=getArguments().getString("title");
         
        // Set title on text view
        textView.setText(sTitle);
 
        // return view
        return view;
    }
}


这是我们应用程序的最终输出。

输出: