【问题标题】:Add button next to each tab in android在android中的每个选项卡旁边添加按钮
【发布时间】:2020-01-29 10:30:57
【问题描述】:

我需要创建一个动态选项卡主机,其中涉及动态添加和删除选项卡。我能够动态添加和删除标签。但我需要在每个选项卡中都有删除按钮。还需要区分标签点击和删除标签点击的点击。请参考图片。我用谷歌搜索到每个标签添加按钮,找不到任何帮助。

编辑: 我已将自定义视图添加到 tablayout。但我需要执行,单击关闭按钮以删除选项卡。我已经想出了如何添加和删除选项卡。但我不知道如何获取关闭按钮的点击监听器。

custom_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/tab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@string/font_fontFamily_medium"
        android:gravity="center_horizontal"
        android:textColor="@color/colorAccent"
        android:textSize="@dimen/tab_label" />

    <Button
        android:background="@drawable/close"
        android:id="@+id/btnClose"
        android:layout_width="40dp"
        android:layout_height="40dp"
        />
</LinearLayout>

MainActivity 和适配器:

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();
    }

    /**
     * Adding custom view to tab
     */
    private void setupTabIcons() {


        View rootView1 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        TextView tabOne = rootView1.findViewById(R.id.tab);

        tabOne.setText("ONE");

        tabLayout.getTabAt(0).setCustomView(rootView1);

        View rootView2 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        TextView tabTwo = rootView2.findViewById(R.id.tab);
        tabTwo.setText("TWO");

        tabLayout.getTabAt(1).setCustomView(rootView2);

        View rootView3 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        TextView tabThree = rootView3.findViewById(R.id.tab);
        tabThree.setText("THREE");

        tabLayout.getTabAt(2).setCustomView(rootView3);


    }

    /**
     * Adding fragments to ViewPager
     *
     * @param viewPager
     */
    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new OneFragment(), "ONE");
        adapter.addFrag(new TwoFragment(), "TWO");
        adapter.addFrag(new ThreeFragment(), "THREE");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();
        private String tabTitles[] = new String[]{"Tab1", "Tab2", "Tab3"};
        private int[] imageResId = {R.drawable.ic_tab_contacts, R.drawable.ic_tab_call, R.drawable.ic_tab_favourite};

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }


    }
}

activity_main.xml:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="@dimen/custom_tab_layout_height"
            app:tabMode="fixed"
            app:tabGravity="fill"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

【问题讨论】:

  • 尝试创建您的 customTab 视图
  • 放上你的相关代码和设计。
  • 如果您使用TabLayout,您可以将CustomView 设置为选项卡。使用yourTab.setCustomView(yourCustomView);
  • 在设置自定义视图的同时,我们可以为图像和文本设置单独的点击监听器吗?

标签: android tabs


【解决方案1】:

我刚刚创建了要删除选项卡的小程序,还删除了图像视图单击上的片段布局,以便更好地理解签出代码:

Removable tab layout

activity_main.xml:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="?attr/actionBarSize"
    android:padding="@dimen/activity_horizontal_margin"
    android:orientation="vertical">



    <Button
        android:id="@+id/btnScrollableTabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn_scrollable_tabs"
        android:layout_marginTop="@dimen/btn_margin_top"
        android:textSize="15dp" />



</LinearLayout>

MainActivity.java:

公共类 MainActivity 扩展 AppCompatActivity 实现 View.OnClickListener {

private Toolbar toolbar;
private Button  btnScrollableTabs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    btnScrollableTabs = (Button) findViewById(R.id.btnScrollableTabs);



    btnScrollableTabs.setOnClickListener(this);


}

@Override
public void onClick(View view) {
    switch (view.getId()) {

        case R.id.btnScrollableTabs:
            startActivity(new Intent(MainActivity.this, ScrollableTabsActivity.class));
            break;
    }
}

}

activity_scrollabel_tab.xml:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

ScrollableTabsActivity 和 ViewPager :

公共类 ScrollableTabsActivity 扩展 AppCompatActivity {

int NumberOfTab = 5;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
ViewPagerAdapter adapter ;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scrollable_tabs);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    adapter = new ViewPagerAdapter(getSupportFragmentManager());
    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

    int length = tabLayout.getTabCount();

    for (int i = 0; i < length; i++) {
        tabLayout.getTabAt(i).setCustomView(getTabView(i));
    }

}

public View getTabView(final int position) {
    View view = LayoutInflater.from(this).inflate(R.layout.close_tablayout, null);
    TextView title = (TextView) view.findViewById(R.id.title);
    ImageView icon = (ImageView) view.findViewById(R.id.close);
    title.setText(adapter.getPageTitle(position));
    icon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NumberOfTab = NumberOfTab - 1;
            setupViewPager(viewPager);
            tabLayout.setupWithViewPager(viewPager);
            if (tabLayout.getTabCount()==3)
                tabLayout.setTabMode(TabLayout.MODE_FIXED);

            int length = tabLayout.getTabCount();
            for (int i = 0; i < length; i++) {
                tabLayout.getTabAt(i).setCustomView(getTabView(i));
            }


        }
    });

    return view;
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        final Fragment result;
        switch (position) {
            case 0:
                // First Fragment of First Tab
                result = new OneFragment();
                break;
            case 1:
                // First Fragment of Second Tab
                result = new TwoFragment();
                break;
            case 2:
                // First Fragment of Second Tab
                result = new ThreeFragment();
                break;
            case 3:
                // First Fragment of Second Tab
                result = new FourFragment();
                break;

            case 4:
                // First Fragment of Second Tab
                result = new FiveFragment();
                break;

            default:
                result = null;
                break;
        }

        // Log.d("RESULT",result.getTag());
        return result;
    }

    @Override
    public int getCount() {
        return NumberOfTab;
    }

    @Override
    public CharSequence getPageTitle(final int position) {
        switch (position) {
            case 0:
                return "One";
            case 1:
                return "Two";
            case 2:
                return "Three";
            case 3:
                return "Four";
            case 4:
                return "Five";
            default:
                return null;
        }
    }

}

}

custom_tabs_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:text="Title"
    android:textColor="@color/windowBackground">

</TextView>

<ImageView
    android:id="@+id/close"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_margin="4dp"
    android:layout_toEndOf="@+id/title"
    android:layout_toRightOf="@+id/title"
    android:src="@drawable/ic_close_black_24dp">

</ImageView>

【讨论】:

    【解决方案2】:

    创建点击监听器,

    View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case 1:
                        Toast.makeText(CircleActivity.this, "1", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(CircleActivity.this, "2", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        Toast.makeText(CircleActivity.this, "Default", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
    

    修改您的 setupTabIcons() 方法,我只是删除一些样板代码,

     private void setupTabIcons() {
            String[] arrTabTile = new String[]{"ONE", "TWO", "THREE"};
            for (int i = 0; i < arrTabTile.length; i++) {
                View rootView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
                TextView tabOne = rootView.findViewById(R.id.tab);
                tabOne.setText(arrTabTile[i]);
                Button btnClose = rootView.findViewById(R.id.btnClose);
                btnClose.setId(i + 1);
                btnClose.setOnClickListener(onClickListener);
                tabLayout.getTabAt(i).setCustomView(rootView);
            }
        }
    

    这里是解释:

    btnClose.setId(i + 1);//use to idntify uniq button
    btnClose.setOnClickListener(onClickListener);//assign click listener
    

    【讨论】:

      【解决方案3】:

      您几乎已经自己实现了解决方案。根据您的代码,可以通过以下方式为每个按钮添加不同的点击侦听器:

          private void setupTabIcons() {
      
              View rootView1 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
              TextView tabOne = rootView1.findViewById(R.id.tab);
              Button buttonOne = rootView1.findViewById(R.id.btnClose);
              tabOne.setText("ONE");
      
              tabLayout.getTabAt(0).setCustomView(rootView1);
      
              View rootView2 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
              TextView tabTwo = rootView2.findViewById(R.id.tab);
              Button buttonTwo = rootView2.findViewById(R.id.btnClose);
              tabTwo.setText("TWO");
      
              tabLayout.getTabAt(1).setCustomView(rootView2);
      
              View rootView3 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
              TextView tabThree = rootView3.findViewById(R.id.tab);
              Button buttonThree = rootView3.findViewById(R.id.btnClose);
              tabThree.setText("THREE");
      
              tabLayout.getTabAt(2).setCustomView(rootView3);
              buttonOne.setOnClickListener(new View.OnClickListener() {
      
                  @Override
                  public void onClick(View view) {
                      Toast.makeText(Main2Activity.this, "Button One clicked!", Toast.LENGTH_SHORT).show();
                  }
              });
              buttonTwo.setOnClickListener(new View.OnClickListener() {
      
                  @Override
                  public void onClick(View view) {
                      Toast.makeText(Main2Activity.this, "Button Two clicked!", Toast.LENGTH_SHORT).show();
                  }
              });
              buttonThree.setOnClickListener(new View.OnClickListener() {
      
                  @Override
                  public void onClick(View view) {
                      Toast.makeText(Main2Activity.this, "Button Three clicked!", Toast.LENGTH_SHORT).show();
                  }
              });
          }
      

      就像您可以获得对每个自定义视图的 TextView 的引用并更改其文本一样,您可以获得对相应按钮的引用并设置自定义点击侦听器。如果您只是将 setupTabIcons() 替换为提供的方法,则当您单击每个关闭按钮时,屏幕上会显示不同的错误消息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-06
        • 2013-11-27
        • 2012-10-03
        • 2012-08-06
        • 2019-12-20
        • 2013-09-16
        • 2013-10-01
        • 1970-01-01
        相关资源
        最近更新 更多