📌  相关文章
📜  如何在 Android 中实现动态 TabLayout?

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

如何在 Android 中实现动态 TabLayout?

在本文中,我们将学习如何在应用程序中使用 ViewPager 添加动态 TabLayout。 TabLayout 提供水平布局来显示选项卡。在这里,我们将只指定我们想要的选项卡数量。 WhatsApp、Facebook 等是带有 ViewPager 的 TabLayout 的一个很好的例子。下面给出了一个示例 GIF,以了解我们将在本文中做什么。请注意,我们将使用Java语言来实现这个项目。

在 Android 中实现动态 TabLayout

分步实施

第 1 步:创建一个新项目

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

第二步:添加依赖



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

在这个项目中,我们正在创建这些文件:

  •  一个名为DynamicFragmentAdapter 的Java文件
  • 一个名为DynamicFragment 的Fragment
  •  名称为DynamicActivity 的一项活动

第 3 步:使用 DynamicFragmentAdapter。 Java文件

转到DynamicFragmentAdapterJava文件,参考如下代码。

// returnthe mNumOfTabs
@Override
public int getCount() {
    return mNumOfTabs;
}

下面是DynamicFragmentAdapter的代码。 Java文件。

Java
import android.os.Bundle;
  
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
  
public class DynamicFragmentAdapter extends FragmentStatePagerAdapter {
    private int mNumOfTabs;
  
    DynamicFragmentAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }
  
    // get the current item with position number
    @Override
    public Fragment getItem(int position) {
        Bundle b = new Bundle();
        b.putInt("position", position);
        Fragment frag = DynamicFragment.newInstance();
        frag.setArguments(b);
        return frag;
    }
  
    // get total number of tabs
    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}


XML


  
    
  


Java
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
  
public class DynamicFragment extends Fragment {
      
    public static DynamicFragment newInstance() {
        return new DynamicFragment();
    }
  
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
  
    // adding the layout with inflater
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dynamic, container, false);
        initViews(view);
        return view;
    }
  
    // initialise the categories
    private void initViews(View view) {
        TextView textView = view.findViewById(R.id.commonTextView);
        textView.setText(String.valueOf("Category :  " + getArguments().getInt("position")));
    }
  
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
  
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }
  
    // pause function call
    @Override
    public void onPause() {
        super.onPause();
    }
  
    // resume function call
    @Override
    public void onResume() {
        super.onResume();
    }
  
    // stop when we close
    @Override
    public void onStop() {
        super.onStop();
    }
  
    // destroy the view
    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
  
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}


XML


  
    
  
        
  
    
  
    
  
        
  
    
      


Java
import android.os.Bundle;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
  
import com.google.android.material.tabs.TabLayout;
  
public class DynamicActivity extends AppCompatActivity {
  
    private ViewPager viewPager;
    private TabLayout mTabLayout;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic);
        initViews();
    }
  
    private void initViews() {
          
        // initialise the layout
        viewPager = findViewById(R.id.viewpager);
        mTabLayout = findViewById(R.id.tabs);
          
        // setOffscreenPageLimit means number 
        // of tabs to be shown in one page
        viewPager.setOffscreenPageLimit(5);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // setCurrentItem as the tab position
                viewPager.setCurrentItem(tab.getPosition());
            }
  
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
  
            }
  
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
  
            }
        });
        setDynamicFragmentToTabLayout();
    }
      
    // show all the tab using DynamicFragmnetAdapter
    private void setDynamicFragmentToTabLayout() {
        // here we have given 10 as the tab number
        // you can give any number here
        for (int i = 0; i < 10; i++) {
            // set the tab name as "Page: " + i
            mTabLayout.addTab(mTabLayout.newTab().setText("Page: " + i));
        }
        DynamicFragmentAdapter mDynamicFragmentAdapter = new DynamicFragmentAdapter(getSupportFragmentManager(), mTabLayout.getTabCount());
          
        // set the adapter
        viewPager.setAdapter(mDynamicFragmentAdapter);
          
        // set the current item as 0 (when app opens for first time)
        viewPager.setCurrentItem(0);
    }
}


步骤 4:使用 fragment_dynamic.xml 文件



转到fragment_dynamic.xml并参考以下代码。下面是fragment_dynamic.xml文件的代码

XML



  
    
  

第 5 步:使用 DynamicFragment。 Java文件

转到动态片段。 Java文件,参考如下代码。

// initialise the categories
private void initViews(View view) {
   TextView textView=view.findViewById(R.id.commonTextView);
   textView.setText(String.valueOf("Category :  "+getArguments().getInt("position")));
}

下面是DynamicFragment的代码。 Java文件。

Java

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
  
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
  
public class DynamicFragment extends Fragment {
      
    public static DynamicFragment newInstance() {
        return new DynamicFragment();
    }
  
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
  
    // adding the layout with inflater
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dynamic, container, false);
        initViews(view);
        return view;
    }
  
    // initialise the categories
    private void initViews(View view) {
        TextView textView = view.findViewById(R.id.commonTextView);
        textView.setText(String.valueOf("Category :  " + getArguments().getInt("position")));
    }
  
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
  
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }
  
    // pause function call
    @Override
    public void onPause() {
        super.onPause();
    }
  
    // resume function call
    @Override
    public void onResume() {
        super.onResume();
    }
  
    // stop when we close
    @Override
    public void onStop() {
        super.onStop();
    }
  
    // destroy the view
    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
  
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

步骤 6:使用 activity_dynamic.xml 文件

转到activity_dynamic.xml文件并参考以下代码。下面是activity_dynamic.xml文件的代码

XML



  
    
  
        
  
    
  
    
  
        
  
    
      

第 7 步:使用 DynamicActivity。 Java文件

转到动态活动。 Java文件,参考如下代码。

// show all the tab using DynamicFragmnetAdapter
private void setDynamicFragmentToTabLayout() {
  for (int i = 0; i < 10; i++) {
         mTabLayout.addTab(mTabLayout.newTab().setText("Page: " + i));
    }
DynamicFragmentAdapter mDynamicFragmentAdapter = new DynamicFragmentAdapter(getSupportFragmentManager(), mTabLayout.getTabCount());
viewPager.setAdapter(mDynamicFragmentAdapter);
viewPager.setCurrentItem(0);
}

下面是DynamicActivity的代码。 Java文件

Java

import android.os.Bundle;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
  
import com.google.android.material.tabs.TabLayout;
  
public class DynamicActivity extends AppCompatActivity {
  
    private ViewPager viewPager;
    private TabLayout mTabLayout;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic);
        initViews();
    }
  
    private void initViews() {
          
        // initialise the layout
        viewPager = findViewById(R.id.viewpager);
        mTabLayout = findViewById(R.id.tabs);
          
        // setOffscreenPageLimit means number 
        // of tabs to be shown in one page
        viewPager.setOffscreenPageLimit(5);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // setCurrentItem as the tab position
                viewPager.setCurrentItem(tab.getPosition());
            }
  
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
  
            }
  
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
  
            }
        });
        setDynamicFragmentToTabLayout();
    }
      
    // show all the tab using DynamicFragmnetAdapter
    private void setDynamicFragmentToTabLayout() {
        // here we have given 10 as the tab number
        // you can give any number here
        for (int i = 0; i < 10; i++) {
            // set the tab name as "Page: " + i
            mTabLayout.addTab(mTabLayout.newTab().setText("Page: " + i));
        }
        DynamicFragmentAdapter mDynamicFragmentAdapter = new DynamicFragmentAdapter(getSupportFragmentManager(), mTabLayout.getTabCount());
          
        // set the adapter
        viewPager.setAdapter(mDynamicFragmentAdapter);
          
        // set the current item as 0 (when app opens for first time)
        viewPager.setCurrentItem(0);
    }
}

输出: