I use Material TabLayout:
<com.google.android.material.tabs.TabItem
android:text="item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/item1" />
<com.google.android.material.tabs.TabItem
android:icon="#drawable/item2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item2"
/>
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item3"/>
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item4" />
</com.google.android.material.tabs.TabLayout>
and androidx ViewPager.
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentPagerAdapter
{
private List<Fragment> fragmentList=new ArrayList<>();
private List<String> fragmentTitleList=new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return fragmentTitleList.size();
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
public void addPage(Fragment fragment, String title)
{
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
}
But when i add my Fragments with addPage() method to viewpager, the icon and text of TabLayout change To my title which add in addPage()(icon remove).
But i want to title be my text and icon which set in TabItem.
Is there any way to do this?
I think you should follow below code make a custom tab layout for you tabs
[1]. 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="match_parent"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:id="#+id/tabImg"
android:layout_width="wrap_content"
android:layout_height="20dp" />
<TextView
android:id="#+id/tabContent"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginStart="#dimen/_5sdp"
android:layout_marginEnd="#dimen/_5sdp"
android:gravity="center"
android:text=""
android:textAlignment="center"
android:textColor="#color/white" />
</LinearLayout>
[2]. Your Activity
private String[] tabTitles = {"Pending", "Ongoing", "Completed"};
private int[] tabIcons = {android.R.drawable.arrow_down_float,android.R.drawable.checkbox_off_background, android.R.drawable.checkbox_on_background};
TextView tabContent;
private void setUpTabIcon() {
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
for (int i = 0; i < tabLayout.getTabCount(); i++) {
LinearLayout tabLinearLayout = (LinearLayout) LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null);
TextView tabContent = (TextView) tabLinearLayout.findViewById(R.id.tabContent);
ImageView tabImg = tabLinearLayout.findViewById(R.id.tabImg);
if (i == 0) {
tabContent.setText(tabTitles[i]);
tabImg.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.white), android.graphics.PorterDuff.Mode.MULTIPLY);
}
tabImg.setImageResource(tabIcons[i]);
tabLayout.getTabAt(i).setCustomView(tabLinearLayout);
}
Log.e(TAG, "onCreate: " + tabLayout.getTabCount());
pageAdapter = new ViewPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
binding.viewPager.setAdapter(pageAdapter);
binding.viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
pageAdapter.notifyDataSetChanged();
}
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
LinearLayout linearLayout = (LinearLayout) tab.getCustomView();
TextView text = (TextView) linearLayout.findViewById(R.id.tabContent);
ImageView img = linearLayout.findViewById(R.id.tabImg);
if (text != null) {
text.setText(tabTitles[tab.getPosition()]);
img.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.white), android.graphics.PorterDuff.Mode.MULTIPLY);
}
binding.viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
LinearLayout linearLayout = (LinearLayout) tab.getCustomView();
TextView tabContent = linearLayout.findViewById(R.id.tabContent);
ImageView img = linearLayout.findViewById(R.id.tabImg);
if (tabContent != null) {
tabContent.setText("");
img.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryDark), android.graphics.PorterDuff.Mode.MULTIPLY);
}
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Related
actvity_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.design.widget.TabLayout
android:id="#+id/tabs"
android:background="#ef9f9f"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
</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>
// MainActivity :
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
public ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
View headerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.custom_tab, null, false);
final LinearLayout linearLayoutOne = (LinearLayout) headerView.findViewById(R.id.ll);
final LinearLayout linearLayout2 = (LinearLayout) headerView.findViewById(R.id.ll2);
final TextView text1 = (TextView) headerView.findViewById(R.id.tvtab1);
final TextView text2 = (TextView) headerView.findViewById(R.id.tvtab2);
tabLayout.getTabAt(0).setCustomView(linearLayoutOne);
tabLayout.getTabAt(1).setCustomView(linearLayout2);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getText().equals("ONE")) {
text1.setVisibility(View.VISIBLE);
} else {
text2.setVisibility(View.VISIBLE);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
if (tab.getText().equals("ONE")) {
text1.setVisibility(View.GONE);
} else {
text2.setVisibility(View.GONE);
}
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
This is my code I want to set custom tab like when i select the first tab then indicator and tab width or weight of the first tab I should increase and second tab decrease show only image not text same if we select the second tab then first tab indicator or weight should decrease and second tab text and image should visibility on:
my current Screen:
in this u can see that tab one is selected image and text are visible tab second is not unselected so the only image is visible no text:
but my Expected tab is like this :
look in this when we select tab then indicator and width of tab increase and tab 2 decreases please suggest me how I will achieve this .thanx
you can easily achieve custom tab with tab layout,
try this one:
public void setupTabView(){
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(R.layout.custom_tab);
TextView tab_name = (TextView) tabLayout.getTabAt(i).getCustomView().findViewById(R.id.txt_tab_name);
tab_name.setText("" + tabNames[i]);
}
}
And make one drawable file with name custom_tab:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txt_tab_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="14sp" />
</RelativeLayout>
Use Below Code .It is have two option.
(i) Create custom TabLayout
(ii) Change custom tablayout text color
(i) Custom TabLayout
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/tab"
android:layout_width="match_parent"
android:textSize="15sp"
android:gravity="center"
android:textColor="#color/txtbox_text_color_darek"
android:layout_height="match_parent"
/>
Source code is:
TextView tabOne = (TextView)
LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("KPIs" + " ");
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.alert_gray,
0);
Objects.requireNonNull(tabLayout.getTabAt(4)).setCustomView(tabOne);
(II) Change Color
private void custom_tablayout_select_unselected_four(final TextView tabOne) {
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (Objects.requireNonNull(tabLayout.getTabAt(4)).isSelected()) {
tabOne.setTextColor(getResources().getColor(R.color.text_color_darkblue));
} else {
tabOne.setTextColor(getResources().getColor(R.color.txtbox_text_color_darek));
}
}
#Override`
public void onTabUnselected(TabLayout.Tab tab) {
// tabOne.setTextColor(Color.GREEN);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
// tabOne.setTextColor(Color.GREEN);
}
});
}
I copied the solution from here, Maybe it will be useful for you
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
TabHost mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1")
.setIndicator((""),getResources().getDrawable(R.drawable.mzl_05))
.setContent(new Intent(this, NearBy.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2")
.setIndicator((""),getResources().getDrawable(R.drawable.mzl_08))
.setContent(new Intent(this, SearchBy.class)));
mTabHost.setCurrentTab(0);
mTabHost.getTabWidget().getChildAt(0).setLayoutParams(new
LinearLayout.LayoutParams((width/2)-2,50));
mTabHost.getTabWidget().getChildAt(1).setLayoutParams(new
LinearLayout.LayoutParams((width/2)-2,50));
You can try another code tabHost.getTabWidget().getChildAt(0).getLayoutParams().width = 50;
Create Custom tab layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal">
<TextView
android:id="#+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#drawable/tab_text_color_selector"
android:textSize="#dimen/medium_text"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_count"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginStart="4dp"
android:background="#drawable/badge_background"
android:gravity="center"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/medium_text"
android:textStyle="bold"
android:visibility="gone" />
</LinearLayout>
tabTitles = new String[]{getString(R.string.main_tab_call), getString(R.string.main_tab_chat), getString(R.string.main_tab_contact)};
private void setupTabIcons() {
for (int i = 0; i < tabTitles.length; i++) {
mTabLayout.getTabAt(i).setCustomView(prepareTabView(i));
}
}
private View prepareTabView(int pos) {
View view = getLayoutInflater().inflate(R.layout.custom_tab, null);
TextView tv_title = view.findViewById(R.id.tv_title);
TextView tv_count = view.findViewById(R.id.tv_count);
tv_title.setText(tabTitles[pos]);
return view;
}
I am currently doing this android tutorial https://www.androidhive.info/2016/05/android-build-intro-slider-app/ .
I want to implement the onClick() event inside the viewpager page like if I clicked the text, it will direct me to another page.
Is it possible? If possible, please help me? Thanks
here is my code for viewPager.
public class welcomeActivity extends AppCompatActivity {
ViewPager viewPager;
private LinearLayout myLinear;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private MyViewPagerAdapter myViewPagerAdapter;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().
setSystemUiVisibility
(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);}
setContentView(R.layout.activity_welcome);
viewPager = (ViewPager) findViewById(R.id.view_pager);
myLinear = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
layouts = new int[]{
R.layout.slide1, R.layout.slide2, R.layout.slide3, R.layout.slide4, R.layout.slide5
};
addBottomDots(0);
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int current = getItem(+1);
if (current < layouts.length){
viewPager.setCurrentItem(current);
}else launchHomeScreen();
}
});
}
ViewPager.OnPageChangeListener viewPagerListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
addBottomDots(position);
if (position == layouts.length -1){
btnSkip.setVisibility(View.GONE);
btnNext.setText("Get Started..");
}
else {
btnNext.setText(getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
myLinear.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
myLinear.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
//prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(welcomeActivity.this, MainActivity.class));
finish();
}
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
public class MyViewPagerAdapter extends PagerAdapter{
private LayoutInflater inflater;
#Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(layouts[position],container,false);
container.addView(v);
return v;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
Here is my layouts. (activity_welcome.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:showIn="#layout/activity_welcome">
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/layoutDots"
android:layout_width="match_parent"
android:layout_height="#dimen/dots_height"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/dots_margin_bottom"
android:gravity="center"
android:orientation="horizontal"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:alpha=".5"
android:layout_above="#id/layoutDots"
android:background="#android:color/white" />
<Button
android:id="#+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#null"
android:text="Next"
android:textColor="#android:color/white" />
<Button
android:id="#+id/btn_skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#null"
android:text="BACK"
android:textColor="#android:color/white" />
</RelativeLayout>
slide1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_screen1">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:layout_width="#dimen/img_width_height"
android:layout_height="#dimen/img_width_height"
android:src="#drawable/ic_food" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/slide_1_title"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_title"
android:textStyle="bold" />
<TextView
android:id="#+id/tvFood"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:paddingLeft="#dimen/desc_padding"
android:paddingRight="#dimen/desc_padding"
android:text="#string/slide_1_desc"
android:textAlignment="center"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_desc" />
</LinearLayout>
</RelativeLayout>
slide2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_screen2">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:layout_width="#dimen/img_width_height"
android:layout_height="#dimen/img_width_height"
android:src="#drawable/ic_movie" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/slide_2_title"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_title"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:paddingLeft="#dimen/desc_padding"
android:paddingRight="#dimen/desc_padding"
android:text="#string/slide_2_desc"
android:textAlignment="center"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_desc" />
</LinearLayout>
</RelativeLayout>
After this line in your adapter :
View v = inflater.inflate(layouts[position],container,false);
Add:
TextView tv =(TextView) v.findViewById(R.id.yourTextView);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do your stuff here whatever you want to do upon click
}});
public class IntroFragment_1 extends Fragment {
private String title;
private int page;
ImageView intro_images_1;
Animation xmlAnimationSample;
// newInstance constructor for creating fragment with arguments
public static IntroFragment_1 newInstance(int page, String title) {
IntroFragment_1 fragmentFirst = new IntroFragment_1();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.intro_view_1, container, false);
intro_images_1 = view.findViewById(R.id.intro_images_1);
xmlAnimationSample = AnimationUtils.loadAnimation(getContext(),R.anim.zoom_intro);
intro_images_1.startAnimation(xmlAnimationSample);
return view;
}
}
MyViewPagerAdapter
public static class MyViewPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 3;
public MyViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return IntroFragment_1.newInstance(0, "Page # 1");
case 1: // Fragment # 0 - This will show FirstFragment different title
return IntroFragment_1.newInstance(0, "Page # 1");
case 2: // Fragment # 1 - This will show SecondFragment
return IntroFragment_1.newInstance(0, "Page # 1");
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
layouts = new int[]{0, 1, 2,};
I have tab Layout with dynamically added custom tabs (Image View + Text View)
I want to change image on select tab and on reselect (2 kind of images)
But there is no click event listeners on Tab, so I added transparent layout to catch clicks.
How do I need to change settings, to make 4 Linear Layouts clickable?
The code:
<RelativeLayout
android:id="#+id/layout_sort_bar_fc"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_alignParentBottom="true">
<android.support.design.widget.TabLayout
android:id="#+id/sort_bar_fc"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabBackground="#color/colorPrimary"
app:tabIndicatorColor="#f00"
app:tabSelectedTextColor="#color/white_text"
app:tabTextColor="#color/colorPrimaryDark"/>
<LinearLayout
android:id="#+id/tab_listenter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/dummy_tab_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0"
android:clickable="true"
android:orientation="horizontal"></LinearLayout>
<LinearLayout
android:id="#+id/dummy_tab_rate"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0"
android:orientation="horizontal"></LinearLayout>
<LinearLayout
android:id="#+id/dummy_tab_change"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0"
android:orientation="horizontal"></LinearLayout>
<LinearLayout
android:id="#+id/dummy_tab_24h"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0"
android:orientation="horizontal"></LinearLayout>
</LinearLayout>
</RelativeLayout>
the following answer deals with somewhat the same question and the answer marked as solution is what you're looking for, it explains how to define and use selectors
Well, you can change image on a selected tab by two method which you need to create in Custom Pager Adapter and call it from tab selected listener.
"MainActivity"
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
createViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
createTabIcons();
adapter.SetOnSelectView(tabLayout,0);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int c = tab.getPosition();
adapter.SetOnSelectView(tabLayout,c);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
int c = tab.getPosition();
adapter.SetUnSelectView(tabLayout,c);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
for (int i = 0; i < tabLayout.getTabCount() - 1; i++) {
View tab = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) tab.getLayoutParams();
p.setMargins(0, 0, 10, 0);
tab.requestLayout();
}
}
private void createTabIcons() {
try {
View tabOne = LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView textView = tabOne.findViewById(R.id.tab);
ImageView imgViewTabIcon = tabOne.findViewById(R.id.imgViewTabIcon);
imgViewTabIcon.setImageResource(R.drawable.img_11);
textView.setText("A");
tabLayout.getTabAt(0).setCustomView(tabOne);
View tabTwo = LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView textView1 = tabTwo.findViewById(R.id.imgViewTabIcon);
textView1.setText("B");
ImageView imgViewTabIcon1 = tabTwo.findViewById(R.id.imgViewTabIcon);
imgViewTabIcon1.setImageResource(R.drawable.img_22);
tabLayout.getTabAt(1).setCustomView(tabTwo);
View tabThree = LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView textView2 = tabThree.findViewById(R.id.tab);
textView2.setText("C");
ImageView imgViewTabIcon2 = tabThree.findViewById(R.id.imgViewTabIcon);
imgViewTabIcon2.setImageResource(R.drawable.img_33);
tabLayout.getTabAt(2).setCustomView(tabThree);
View tabFour = LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView textView3 = tabFour.findViewById(R.id.tab);
textView3.setText("D");
ImageView imgViewTabIcon3 = tabFour.findViewById(R.id.imgViewTabIcon);
imgViewTabIcon3.setImageResource(R.drawable.img_33);
tabLayout.getTabAt(3).setCustomView(tabFour);
} catch (Exception e) {
e.printStackTrace();
}
}
private void createViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager(),HomeActivity.this);
adapter.addFrag(new A(), "A");
adapter.addFrag(new B(), "B");
adapter.addFrag(new C(), "C");
adapter.addFrag(new D(), "D");
viewPager.setAdapter(adapter);
}
}
"Custom PagerAdapter"
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private Context mContext;
public ViewPagerAdapter(FragmentManager manager, Context context) {
super(manager);
mContext=context;
}
#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);
}
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
public void SetOnSelectView(TabLayout tabLayout, int position)
{
TabLayout.Tab tab = tabLayout.getTabAt(position);
View selected = tab.getCustomView();
TextView textView = (TextView) selected.findViewById(R.id.tab);
textView.setTextColor(mContext.getResources().getColor(R.color.colorPrimary));
ImageView imgViewTabIcon = selected.findViewById(R.id.imgViewTabIcon);
int height = dpToPx(35);
if(textView.getText().toString().equals("tab1")){
BitmapDrawable bitmapdraw = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.img_1);
Bitmap b = bitmapdraw.getBitmap();
Bitmap smallMarker = Bitmap.createScaledBitmap(b, height, height, false);
imgViewTabIcon.setImageBitmap(smallMarker);
}else if(textView.getText().toString().equals("tab2")){
BitmapDrawable bitmapdraw = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.img_2);
Bitmap b = bitmapdraw.getBitmap();
Bitmap smallMarker = Bitmap.createScaledBitmap(b, height, height, false);
imgViewTabIcon.setImageBitmap(smallMarker);
}else if(textView.getText().toString().equals("tab3")){
BitmapDrawable bitmapdraw = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.img_3);
Bitmap b = bitmapdraw.getBitmap();
Bitmap smallMarker = Bitmap.createScaledBitmap(b, height, height, false);
imgViewTabIcon.setImageBitmap(smallMarker);
}
else {
BitmapDrawable bitmapdraw = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.img_4);
Bitmap b = bitmapdraw.getBitmap();
Bitmap smallMarker = Bitmap.createScaledBitmap(b, height, height, false);
imgViewTabIcon.setImageBitmap(smallMarker);
}
}
public void SetUnSelectView(TabLayout tabLayout,int position) {
TabLayout.Tab tab = tabLayout.getTabAt(position);
View selected = tab.getCustomView();
TextView textView = (TextView) selected.findViewById(R.id.tab);
textView.setTextColor(mContext.getResources().getColor(R.color.white));
ImageView imgViewTabIcon = selected.findViewById(R.id.imgViewTabIcon);
if(textView.getText().toString().equals("tab1")){
imgViewTabIcon.setImageResource(R.drawable.img_11);
}else if(textView.getText().toString().equals("tab2")){
imgViewTabIcon.setImageResource(R.drawable.img_22);
}else if(textView.getText().toString().equals("tab3")){
imgViewTabIcon.setImageResource(R.drawable.img_33);
}else{
imgViewTabIcon.setImageResource(R.drawable.img_44);
}
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public int getItemPosition(Object object){
return ViewPagerAdapter.POSITION_NONE;
}
}
"Custom Layout for Tab"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/custom_tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/tab_color_selector"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center">
<ImageView
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:id="#+id/imgViewTabIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/img_11" />
<TextView
android:id="#+id/tab"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:padding="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A"
android:textColor="#FFFFFF"
android:layout_gravity="center"
android:textSize="12sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
"MainActivity XML File"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:orientation="vertical"
tools:context=".activity.MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
app:tabBackground="#drawable/tab_color_selector"
app:tabGravity="fill"
app:tabIndicatorColor="#color/gps_btn"
app:tabMode="fixed"
app:tabSelectedTextColor="#ffffff"
app:tabTextColor="#ffffff" />
<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" />
</LinearLayout>
Hello all I simply want to achieve this.But I am not being able to achieve this
I did this to achieve this
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
android:background="#42474b"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<ImageView
android:id="#+id/toolbarlogo"
android:src="#mipmap/toolbarlogo"
android:layout_width="wrap_content"
android:layout_marginRight="200dp"
android:layout_height="46dp"
/>
</android.support.v7.widget.Toolbar>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#494e51"
android:gravity="center_vertical"
android:paddingLeft="40dp"
android:textSize="10dp"
android:textColor="#fff"
android:text="The Ongoing survey closes on Dec 31,2016 at 2:00pm GMT"
/>
<View
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#fff"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabTextAppearance="#style/MineCustomTabText"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:background="#drawable/innerpg_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
and this is my class file
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ongoing,
R.drawable.upcoming,
R.drawable.results
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setPadding(0, getStatusBarHeight(), 0, 0);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
for(int i=0; i < tabLayout.getTabCount(); i++) {
View tab = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) tab.getLayoutParams();
p.setMargins(10, 10, 50, 30);
tab.requestLayout();
}
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Ongoing(), "Ongoing");
adapter.addFrag(new Upcomming(), "Upcomming");
adapter.addFrag(new Result(), "Result");
viewPager.setAdapter(adapter);
}
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
return true;
}
return super.onOptionsItemSelected(item);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
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);
}
}
}
Using above code I am getting tab text below the icon(i mean in two different line).THe next issue is I have set the margin but I dont know how to set the color of margin.The final issue is I want to change the background color of active tab to yellow as shown in image.Please help me fix this issue
try this
private void setupTabIcons() {
LayoutInflater inflater = LayoutInflater.from(this);
View view1 = inflater.inflate(R.layout.custom_view, null, false);
((TextView) view1.findViewById(R.id.text)).setText("Tab1");
((ImageView) view1.findViewById(R.id.image)).setImageResource(tabIcon[0]);
View view2 = inflater.inflate(R.layout.custom_view, null, false);
((TextView) view2.findViewById(R.id.text)).setText("Tab2");
((ImageView) view2.findViewById(R.id.image)).setImageResource(tabIcon[0]);
View view3 = inflater.inflate(R.layout.custom_view, null, false);
((TextView) view3.findViewById(R.id.text)).setText("Tab3");
((ImageView) view3.findViewById(R.id.image)).setImageResource(tabIcon[0]);
tabLayout.getTabAt(0).setCustomView(view1);
tabLayout.getTabAt(1).setCustomView(view2);
tabLayout.getTabAt(2).setCustomView(view3);
your custom view will look like
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
You can Use android:drawableLeft to display drawable on left of
textview properly.
For Different backgroundColor for Different state You can use
android:background for different color state like this
In my android activity I have a radio button group and a tab layout using viewpager.
There are two tabs and 2 radio buttons.
The first tab is an attachment tab
second one is an event tab.
When i checked the first radio button then user is not allowed to see the first tab,so i need to disable the first tab and shows the second tab for the user.If i selected the second radio button i need to enable the first tab and user is allowed to access the first tab.I don't want to remove the tab,i just want to disable it so that user can't access it by swiping or clicking on the tab.
How to do that? Below is my code to show tab.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_asset);
//remaining code
viewPager2 = (ViewPager) findViewById(R.id.viewPager2);
setupViewPager2(viewPager2);
tabLayout2 = (TabLayout) findViewById(R.id.tab_layout2);
tabLayout2.setupWithViewPager(viewPager2);//setting tab over viewpager
rdbGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
}
});
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//Implementing tab selected listener over tablayout
tabLayout2.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager2.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
switch (tab.getPosition()) {
case 0:
Log.e("TAG","TAB1");
break;
case 1:
Log.e("TAG","TAB2");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
//Setting View Pager
private void setupViewPager2(ViewPager viewPager) {
expAttList = new ArrayList<COAAccount>();
adapter2 = new ViewPagerAdapter(getSupportFragmentManager());
adapter2.addFrag(new AttachmentFragment("Attachments",expAttList,fontFamily), "Attachments");
adapter2.addFrag(new EventFragment("Events",fontFamily), "Events");
viewPager2.setAdapter(adapter2);
}
//View Pager fragments setting adapter class
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();//fragment arraylist
private final List<String> mFragmentTitleList = new ArrayList<>();//title arraylist
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
//adding fragments and title method
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
layout file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fab="http://schemas.android.com/apk/res-auto"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="130dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="24dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/Lavender"
android:layout_marginBottom="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/edtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="Name" />
</android.support.design.widget.TextInputLayout>
<RadioGroup
android:id="#+id/rdbGroup"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:background="#drawable/round_border"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/rdb1"
android:layout_width="wrap_content"
android:layout_height="23dp"
android:layout_weight="1"
android:background="#drawable/bg_blue"
android:button="#android:color/transparent"
android:textColor="#drawable/txt_color"
android:gravity="center"
android:paddingBottom="2dp"
android:paddingTop="2dp"
android:singleLine="true"
android:text="radio1"
android:checked="true"
android:textSize="13sp" />
<View
android:id="#+id/vSep2"
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#000000"
android:visibility="visible" />
<RadioButton
android:id="#+id/rdb2"
android:layout_width="wrap_content"
android:layout_height="23dp"
android:layout_weight="1"
android:background="#drawable/bg_red"
android:button="#android:color/transparent"
android:textColor="#drawable/txt_color"
android:gravity="center"
android:paddingBottom="2dp"
android:paddingTop="2dp"
android:singleLine="true"
android:text="radio2"
android:textSize="13sp" />
</RadioGroup>
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/SkyBlue"
android:layout_marginBottom="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabIndicatorColor="#android:color/holo_red_dark"
app:tabIndicatorHeight="4dp"
local:tabMode="scrollable" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPager2"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="#id/tab_layout"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
app:headerLayout="#layout/drawer_header_expense"
app:menu="#menu/drawer"/>
</android.support.v4.widget.DrawerLayout>
It's a tricky one.You need to use a custom ViewPager for this.Below is the code.
Change your ViewPager in xml to this :
<yourPackage.NonSwipeableViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_below="#id/tab_layout"/>
Below is the custom view pager class :
public class NonSwipeableViewPager extends ViewPager {
private boolean enabled;
public NonSwipeableViewPager(Context context) {
super(context);
this.enabled = true;
}
public NonSwipeableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
}
Now in your activity use below code :
NonSwipeableViewPager viewPager = (NonSwipeableViewPager) findViewById(R.id.pager);
//write code to set viewpager to the tablayout that u have already done.Use the same.
rdbGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
pos = rdbGroup.indexOfChild(findViewById(checkedId));
LinearLayout tabStrip = ((LinearLayout)tabLayout.getChildAt(0));
switch (pos) {
case 0:
viewPager.setCurrentItem(1);
viewPager.setPagingEnabled(false);
tabstrip.getChildAt(0).setClickable(false);
tabstrip.getChildAt(0).setEnabled(false);
break;
case 1:
viewPager.setCurrentItem(0);
viewPager.setPagingEnabled(true);
tabstrip.getChildAt(0).setClickable(true);
tabstrip.getChildAt(0).setEnabled(true);
break;
default:
//here add whatever you like
break;
}
}
});
Use the swicth condition as per your requirement.
You can try this:
ViewPager viewPager2;
TabLayout tabLayout2;
ViewPagerAdapter adapter2;
RadioGroup rdbGroup;
RadioButton rdb1, rdb2;
LinearLayout tabstrip;
int pos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//remaining code
viewPager2 = (ViewPager) findViewById(R.id.viewPager2);
setupViewPager2(viewPager2);
tabLayout2 = (TabLayout) findViewById(R.id.tab_layout2);
rdbGroup = (RadioGroup) findViewById(R.id.rdbGroup);
rdb1 = (RadioButton) findViewById(R.id.rdb1);
rdb2 = (RadioButton) findViewById(R.id.rdb2);
tabLayout2.setupWithViewPager(viewPager2);//setting tab over viewpager
//get position of already checked radiobutton
int radioButtonID = rdbGroup.getCheckedRadioButtonId();
View radioButton = rdbGroup.findViewById(radioButtonID);
pos = rdbGroup.indexOfChild(radioButton);
tabstrip = (LinearLayout) tabLayout2.getChildAt(0);
//check which radiobutton is already checked and as per its pos disbale or enable the tabs as below
if (pos == 0) {
tabLayout2.getTabAt(1).select();
tabstrip.getChildAt(0).setClickable(false);
tabstrip.getChildAt(0).setEnabled(false);
} else if (pos == 1) {
tabstrip.getChildAt(0).setClickable(true);
tabstrip.getChildAt(0).setEnabled(true);
}
rdbGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
pos = rdbGroup.indexOfChild(findViewById(checkedId));
switch (pos) {
case 0:
tabstrip.getChildAt(0).setClickable(false);
tabstrip.getChildAt(0).setEnabled(false);
break;
case 1:
tabstrip.getChildAt(0).setClickable(true);
tabstrip.getChildAt(0).setEnabled(true);
break;
default:
//here add whatever you like
tabstrip.getChildAt(0).setClickable(true);
tabstrip.getChildAt(0).setEnabled(true);
break;
}
}
});
//Implementing tab selected listener over tablayout
tabLayout2.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager2.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
switch (tab.getPosition()) {
case 0:
Log.e("TAG", "TAB1");
break;
case 1:
Log.e("TAG", "TAB2");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
//Setting View Pager
private void setupViewPager2(ViewPager viewPager) {
expAttList = new ArrayList<COAAccount>();
expAttList = new ArrayList<COAAccount>();
adapter2 = new ViewPagerAdapter(getSupportFragmentManager());
adapter2.addFrag(new AttachmentFragment("Attachments", expAttList, fontFamily), "Attachments");
adapter2.addFrag(new EventFragment("Events", fontFamily), "Events");
viewPager2.setAdapter(adapter2);
}
//View Pager fragments setting adapter class
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();//fragment arraylist
private final List<String> mFragmentTitleList = new ArrayList<>();//title arraylist
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
//adding fragments and title method
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}