在Android中每个选项卡旁边添加按钮

时间:2019-09-30 06:39:17

标签: android tabs

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

编辑: 我已将自定义视图添加到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>

3 个答案:

答案 0 :(得分:4)

创建Click侦听器,

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

答案 1 :(得分:2)

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

    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(),则单击每个关闭按钮时,屏幕上会显示不同的错误消息。

答案 2 :(得分:0)

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

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>

相关问题