Manikandan
Manikandan

Reputation: 1519

Add button next to each tab in android

I need to create a dynamic tabhost, which involves, adding and removing tabs dynamically. I'm able to add and remove tabs dynamically. But I need to have delete button in each tab. Also need to differentiate the click for tab click and delete tab click. Kindly refer the image. I have googled to add button to each tab, couldn't find any help. enter image description here

Edit: I have added custom view to tablayout. But I need to perform, click on close button to remove the tab. I have figured how to how to add and remove a tab. But I couldn't figure out how to get the click listener for the close button.

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 and Adapter:

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>

Upvotes: 2

Views: 3721

Answers (3)

Jaspalsinh Gohil
Jaspalsinh Gohil

Reputation: 704

I have Just create Small Programme to Remove tab and also remove fragment layout on image view click for better understanding check out code:

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:

public class MainActivity extends AppCompatActivity implements 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 and ViewPager :

public class ScrollableTabsActivity extends 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>

Upvotes: 0

Kintan Patel
Kintan Patel

Reputation: 1278

Create Click listener,

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;
            }
        }
    };

Modify your setupTabIcons() method i just remove some boilerplate code,

 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);
        }
    }

Here is explanation:

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

Upvotes: 4

gmetal
gmetal

Reputation: 2988

You have almost implemented the solution yourself. Based on your code, adding a different click listener per button can be achieved with something like this:

    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();
            }
        });
    }

Much like you can get a reference to the TextView per custom view and change its text, you can get a reference to the corresponding button and set a custom click listener. If you just replace your setupTabIcons() with the provided method, when you click each close button you will get a different error message displayed on the screen.

Upvotes: 2

Related Questions