📜  Android 中的协调器 TabLayout

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

Android 中的协调器 TabLayout

许多应用程序使用 TabLayout,其中我们必须在 TabLayout 上方显示图像。这种类型的 UI 设计主要见于餐厅应用程序等等。在本文中,我们将看看使用 Android Studio 在我们的 Android 应用程序中使用 Coordinator TabLayout 实现相同类型的视图。

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

我们将构建一个简单的应用程序,我们将在其中显示图像,并在图像下方显示一个 TabLayout。在该 TabLayout 中,我们将在该列表中显示与课程相关的详细信息,并将在其中显示不同类型的课程。下面给出了一个示例视频,以了解我们将在本文中做什么。请注意,我们将使用Java语言来实现这个项目。

Android中添加Coordinator TabLayout的分步实现

第 1 步:创建一个新项目

要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。请注意,选择Java作为编程语言。

第 2 步:在 build.gradle 中添加使用 Coordinator Layout 的依赖项



导航到Gradle Scripts > build.gradle(Module:app)并在依赖项部分添加以下依赖项。

implementation 'cn.hugeterry.coordinatortablayout:coordinatortablayout:1.2.2'

添加依赖项后,现在同步项目,我们将准备好处理它。

第 3 步:更新 themes.xml 文件。

导航到app > res > values > themes.xml并将主题更改为NoActionBar 。参考以下代码。

XML

    
    


XML


  
    
    
  
        
        
  
    
      


XML


  
    
    
  


XML


      
    
    
      


Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.List;
  
public class RecyclerAdapter extends RecyclerView.Adapter {
      
    // creating variables for context and list.
    private Context mContext;
    private List mDatas;
  
    // creating constructor.
    public RecyclerAdapter(Context context, List datas) {
        mContext = context;
        mDatas = datas;
    }
  
    @NonNull
    @Override
    public RecyclerAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // inflating layout on below line.
        return new MyViewHolder(LayoutInflater.from(
                mContext).inflate(R.layout.item_main, parent, false));
    }
  
    @Override
    public void onBindViewHolder(@NonNull RecyclerAdapter.MyViewHolder holder, int position) {
        // setting data to text view on below line.
        holder.tv.setText(mDatas.get(position));
    }
  
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return mDatas.size();
    }
  
    public class MyViewHolder extends RecyclerView.ViewHolder {
        // creating variables for text view.
        TextView tv;
  
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing the text view.
            tv = (TextView) itemView.findViewById(R.id.tv_num);
        }
    }
}


Java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
  
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
import java.util.List;
  
public class HomeFragment extends Fragment {
      
    // creating a variables on below line.
    private static final String ARG_TITLE = "title";
    private RecyclerView mRecyclerView;
    private List courseList;
    private String mTitle;
  
    public HomeFragment() {
        // Required empty public constructor
    }
  
    // creating a get instance method to get the data which we passed.
    public static HomeFragment getInstance(String title) {
        HomeFragment fra = new HomeFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_TITLE, title);
        fra.setArguments(bundle);
        return fra;
    }
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // on below line we are getting the data from bundles.
        Bundle bundle = getArguments();
        mTitle = bundle.getString(ARG_TITLE);
    }
  
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        // below method is use to load data in our array list.
        initData(mTitle);
        // initialing our variables for views.
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mRecyclerView.getContext()));
        mRecyclerView.setAdapter(new RecyclerAdapter(mRecyclerView.getContext(), courseList));
        return view;
    }
  
    private void initData(String heading) {
        // running a switch case to add data to our array list.
        switch (heading) {
            case "DSA":
                courseList = new ArrayList<>();
                courseList.add("Arrays");
                courseList.add("Recursion");
                courseList.add("Hashing");
                courseList.add("Binary Search Trees");
                courseList.add("Searching");
                courseList.add("Sorting");
                break;
            case "C++":
                courseList = new ArrayList<>();
                courseList.add("Variables");
                courseList.add("Data Types");
                courseList.add("Type Conversion");
                courseList.add("Operators");
                courseList.add("Sorting");
                courseList.add("C++ Syntax");
                courseList.add("Pointers");
                break;
            case "Java":
                courseList = new ArrayList<>();
                courseList.add("Intro to Java");
                courseList.add("Object Oriented Concepts");
                courseList.add("Variables");
                courseList.add("Conditional and Control Flow");
                courseList.add("Array List");
                break;
            default:
                courseList = new ArrayList<>();
                courseList.add("Basic Concepts of Python");
                courseList.add("Program Flow Control in Python");
                courseList.add("Lists and Tuples");
                courseList.add("Functions");
                courseList.add("Python Dictonaries and Sets");
                break;
        }
    }
}


Java
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
  
import java.util.ArrayList;
  
public class ViewPagerAdapter extends FragmentPagerAdapter {
      
    // creating a string array for tab title.
    private final String[] mTitles;
      
    // creating an array list on below line for fragments.
    private ArrayList mFragments = new ArrayList<>();
  
    // constructor for view pager
    public ViewPagerAdapter(FragmentManager fm, ArrayList mFragments, String[] mTitles) {
        super(fm);
        this.mFragments = mFragments;
        this.mTitles = mTitles;
    }
  
    // returning the size of our list.
    @Override
    public int getCount() {
        return mFragments.size();
    }
  
    // below method is to set the title for tab layout item.
    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles[position];
    }
  
    // below method is use to get the item.
    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }
  
}


Java
import android.os.Bundle;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
  
import java.util.ArrayList;
  
import cn.hugeterry.coordinatortablayout.CoordinatorTabLayout;
  
public class MainActivity extends AppCompatActivity {
      
    // creating variables for coordinator layout
    private CoordinatorTabLayout mCoordinatorTabLayout;
      
    // creating an integer array for images and colors.
    private int[] mImageArray, mColorArray;
      
    // creating array list for our fragments.
    private ArrayList mFragments;
      
    // creating a string array for our tab title in tab layout.
    private final String[] mTitles = {"DSA", "Java", "C++", "Python"};
      
    // creating a variable for view pager.
    private ViewPager mViewPager;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // calling method to initialize 
        // our fragments and view pager.
        initFragments();
        initViewPager();
          
        // adding images to our int array on below line.
        mImageArray = new int[]{
                R.drawable.dsa,
                R.drawable.java,
                R.drawable.cpp,
                R.drawable.python};
          
        // adding color to our color array on below line.
        mColorArray = new int[]{
                android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_green_light};
          
        // initializing our coordinator layout
        mCoordinatorTabLayout = findViewById(R.id.coordinatortablayout);
          
        // on below line we are setting title to our tool bar
        // and image array, color array and view pager
        // to our co coordinator layout
        mCoordinatorTabLayout.setTranslucentStatusBar(this)
                .setTitle("Geeks For Geeks")
                .setBackEnable(true)
                .setImageArray(mImageArray, mColorArray)
                .setupWithViewPager(mViewPager);
    }
  
    private void initFragments() {
          
        // initializing our array list.
        mFragments = new ArrayList<>();
         
        // adding fragment to our array list on below line.
        for (String title : mTitles) {
            mFragments.add(HomeFragment.getInstance(title));
        }
    }
  
    private void initViewPager() {
        // initializing our view pager and setting adapter to it.
        mViewPager = findViewById(R.id.vp);
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), mFragments, mTitles));
    }
}


步骤 4:使用 activity_main.xml 文件

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

XML





  
    
    
  
        
        
  
    
      

第 5 步:创建一个片段来显示我们的课程详细信息

导航到应用程序 > res > layout > 右键单击它 > New > Blank Fragment并将其命名为HomeFragment并单击 Create 创建一个新 Fragment。创建此片段后,现在导航到app > res > layout > fragment_home并将以下代码添加到其中。

XML



  
    
    
  

第六步:为RecyclerView的item新建一个布局文件

导航到app > res > layout > 右键单击它 > New > Layout Resource file并将其命名为item_main并向其添加以下代码。

XML



      
    
    
      

第 7 步:创建一个适配器类,用于为 RecyclerView 项设置数据

导航到应用程序 > Java > 您应用程序的包名称 > 右键单击它 > 新建 > Java类并将其命名为RecyclerAdapter并将以下代码添加到其中。

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.List;
  
public class RecyclerAdapter extends RecyclerView.Adapter {
      
    // creating variables for context and list.
    private Context mContext;
    private List mDatas;
  
    // creating constructor.
    public RecyclerAdapter(Context context, List datas) {
        mContext = context;
        mDatas = datas;
    }
  
    @NonNull
    @Override
    public RecyclerAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // inflating layout on below line.
        return new MyViewHolder(LayoutInflater.from(
                mContext).inflate(R.layout.item_main, parent, false));
    }
  
    @Override
    public void onBindViewHolder(@NonNull RecyclerAdapter.MyViewHolder holder, int position) {
        // setting data to text view on below line.
        holder.tv.setText(mDatas.get(position));
    }
  
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return mDatas.size();
    }
  
    public class MyViewHolder extends RecyclerView.ViewHolder {
        // creating variables for text view.
        TextView tv;
  
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing the text view.
            tv = (TextView) itemView.findViewById(R.id.tv_num);
        }
    }
}

第 8 步:使用 HomeFragment。 Java文件



导航到应用程序 > Java > 您应用程序的包名称 > HomeFragment。 Java文件并将以下代码添加到其中。

Java

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
  
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.ArrayList;
import java.util.List;
  
public class HomeFragment extends Fragment {
      
    // creating a variables on below line.
    private static final String ARG_TITLE = "title";
    private RecyclerView mRecyclerView;
    private List courseList;
    private String mTitle;
  
    public HomeFragment() {
        // Required empty public constructor
    }
  
    // creating a get instance method to get the data which we passed.
    public static HomeFragment getInstance(String title) {
        HomeFragment fra = new HomeFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_TITLE, title);
        fra.setArguments(bundle);
        return fra;
    }
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // on below line we are getting the data from bundles.
        Bundle bundle = getArguments();
        mTitle = bundle.getString(ARG_TITLE);
    }
  
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        // below method is use to load data in our array list.
        initData(mTitle);
        // initialing our variables for views.
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mRecyclerView.getContext()));
        mRecyclerView.setAdapter(new RecyclerAdapter(mRecyclerView.getContext(), courseList));
        return view;
    }
  
    private void initData(String heading) {
        // running a switch case to add data to our array list.
        switch (heading) {
            case "DSA":
                courseList = new ArrayList<>();
                courseList.add("Arrays");
                courseList.add("Recursion");
                courseList.add("Hashing");
                courseList.add("Binary Search Trees");
                courseList.add("Searching");
                courseList.add("Sorting");
                break;
            case "C++":
                courseList = new ArrayList<>();
                courseList.add("Variables");
                courseList.add("Data Types");
                courseList.add("Type Conversion");
                courseList.add("Operators");
                courseList.add("Sorting");
                courseList.add("C++ Syntax");
                courseList.add("Pointers");
                break;
            case "Java":
                courseList = new ArrayList<>();
                courseList.add("Intro to Java");
                courseList.add("Object Oriented Concepts");
                courseList.add("Variables");
                courseList.add("Conditional and Control Flow");
                courseList.add("Array List");
                break;
            default:
                courseList = new ArrayList<>();
                courseList.add("Basic Concepts of Python");
                courseList.add("Program Flow Control in Python");
                courseList.add("Lists and Tuples");
                courseList.add("Functions");
                courseList.add("Python Dictonaries and Sets");
                break;
        }
    }
}

步骤 9:创建用于处理 TabLayout 的 Adapter 类

导航到应用程序 > Java > 您应用程序的包名称 > 右键单击它 > 新建 > Java类并将其命名为ViewPagerAdapter并将以下代码添加到其中。

Java

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
  
import java.util.ArrayList;
  
public class ViewPagerAdapter extends FragmentPagerAdapter {
      
    // creating a string array for tab title.
    private final String[] mTitles;
      
    // creating an array list on below line for fragments.
    private ArrayList mFragments = new ArrayList<>();
  
    // constructor for view pager
    public ViewPagerAdapter(FragmentManager fm, ArrayList mFragments, String[] mTitles) {
        super(fm);
        this.mFragments = mFragments;
        this.mTitles = mTitles;
    }
  
    // returning the size of our list.
    @Override
    public int getCount() {
        return mFragments.size();
    }
  
    // below method is to set the title for tab layout item.
    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles[position];
    }
  
    // below method is use to get the item.
    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }
  
}

第 10 步:使用MainActivity。 Java文件

转到主活动。 Java文件,参考如下代码。下面是MainActivity的代码。 Java文件。代码中添加了注释以更详细地理解代码。

Java

import android.os.Bundle;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
  
import java.util.ArrayList;
  
import cn.hugeterry.coordinatortablayout.CoordinatorTabLayout;
  
public class MainActivity extends AppCompatActivity {
      
    // creating variables for coordinator layout
    private CoordinatorTabLayout mCoordinatorTabLayout;
      
    // creating an integer array for images and colors.
    private int[] mImageArray, mColorArray;
      
    // creating array list for our fragments.
    private ArrayList mFragments;
      
    // creating a string array for our tab title in tab layout.
    private final String[] mTitles = {"DSA", "Java", "C++", "Python"};
      
    // creating a variable for view pager.
    private ViewPager mViewPager;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // calling method to initialize 
        // our fragments and view pager.
        initFragments();
        initViewPager();
          
        // adding images to our int array on below line.
        mImageArray = new int[]{
                R.drawable.dsa,
                R.drawable.java,
                R.drawable.cpp,
                R.drawable.python};
          
        // adding color to our color array on below line.
        mColorArray = new int[]{
                android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_green_light};
          
        // initializing our coordinator layout
        mCoordinatorTabLayout = findViewById(R.id.coordinatortablayout);
          
        // on below line we are setting title to our tool bar
        // and image array, color array and view pager
        // to our co coordinator layout
        mCoordinatorTabLayout.setTranslucentStatusBar(this)
                .setTitle("Geeks For Geeks")
                .setBackEnable(true)
                .setImageArray(mImageArray, mColorArray)
                .setupWithViewPager(mViewPager);
    }
  
    private void initFragments() {
          
        // initializing our array list.
        mFragments = new ArrayList<>();
         
        // adding fragment to our array list on below line.
        for (String title : mTitles) {
            mFragments.add(HomeFragment.getInstance(title));
        }
    }
  
    private void initViewPager() {
        // initializing our view pager and setting adapter to it.
        mViewPager = findViewById(R.id.vp);
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), mFragments, mTitles));
    }
}

现在运行您的应用程序并查看应用程序的输出。

输出: