Refresh Fragment View on Tab Change - android

Hello I'm implementing a dynamic TabLayout using a single fragment, i have manage to create the tabs so far but there is a problem using a single fragment. When im changing the tabs the fragment view is not updating repeatedly, although im updating the data in the fragment's onCreateView method based on the tab selection. I have a recyclerview in the that fragment which should change according to the tab selection. SO can anyone help me with it or do anyone have a better way of approach?
TabView Activity
public class SubCategory extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
Activity a;
String url;
List<CategoryEncapsulation> categories = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_category);
a=this;
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
categories=((MyshinzGlobal)getApplicationContext()).getCategoryList();
setupViewPager(viewPager);
((MyshinzGlobal)getApplicationContext()).setCategory_id(categories.get(0).getCategory_id());
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
try {
for (int i = 0; i < categories.size(); i++) {
try {
adapter.addFragment(new ListFragment(), categories.get(i).getCategory_name());
} catch (Exception e) {
e.printStackTrace();
}
}
}catch (Exception e) {
e.printStackTrace();
}
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
((MyshinzGlobal)getApplicationContext()).setCategory_id(categories.get(position).getCategory_id());
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
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 int getItemPosition(Object object) {
return super.getItemPosition(object);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Fragment class
public class ListFragment extends Fragment{
String category_id;
Activity a;
RecyclerView rv;
SubCategoryAdapter sca;
List<ParentListItem> parentListItems;
List<CategoryEncapsulation> categories = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.sub_category_fragment, container, false);
a=getActivity();
categories=((MyshinzGlobal)a.getApplicationContext()).getCategoryList();
category_id=((MyshinzGlobal)a.getApplicationContext()).getCategory_id();
parentListItems= new ArrayList<>();
Toast.makeText(getActivity(), String.valueOf(category_id), Toast.LENGTH_SHORT).show();
rv= (RecyclerView) view.findViewById(R.id.recycler_view);
for (int i=0; i<categories.size();i++){
if(categories.get(i).getCategory_id().equals(category_id)){
parentListItems=categories.get(i).getParentListItems();
}
}
sca=new SubCategoryAdapter(a,parentListItems);
rv.setAdapter(sca);
rv.setLayoutManager(new LinearLayoutManager(a));
//new GetAllSubCategoryTask(a,url,"1001").execute();
return view;
}
}

I have two solution for this.
1) make your view pager offset limit 0. Which default 1. If you are switching another fragment which not in offset, that fragment re-creating.
viewPager.setOffscreenPageLimit(0);
2) Tell your adapter, fragment has been changed. So your adapter will re-create its views again.
rv.notifyDataSetChanged();
I hope these will solve your problem.

First thing as you are using ViewPager, onCreateView() of Fragment will be called only when getItem() of FragmentPagerAdapter will be called.
If need to create a method in Fragment which will call RecyclerView.notifyDataSetChanged().
Check out updated code for both classes
TabView Activity
public class SubCategory extends AppCompatActivity {
//....
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
}
private void setupViewPager(ViewPager viewPager) {
//...
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
((MyshinzGlobal)getApplicationContext()).setCategory_id(categories.get(position).getCategory_id());
adapter.getItem(position).listUpdated();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<ListFragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public ListFragment getItem(int position) {
return mFragmentList.get(position);
}
//...
}
}
Fragment class
public class ListFragment extends Fragment {
//...
public void listUpdated() {
for (int i = 0; i < categories.size(); i++) {
if (categories.get(i).getCategory_id().equals(category_id)) {
parentListItems.clear();
parentListItems.addAll(categories.get(i).getParentListItems());
}
}
sca.notifyDataSetChanged();
}
}

Related

Android Fragment Data Pass with TABBED Activity

When i try to retrieve category list from server for multiple tab, after set adapter its Toast two ID for the first time .Suppose, When current tab id is ZERO , then its showing next increment ID .
Like the Screenshot its showing 20 in tab 0 .
Basically i want the category id dynamically when i swipe the tab.
public class Tabtest extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
Toolbar toolbar;
int i;
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabtest);
toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tabLayout=(TabLayout)findViewById(R.id.tabs);
viewPager=(ViewPager)findViewById(R.id.container);
getCategoriesList();
tabLayout.setupWithViewPager(viewPager);
}
public void getCategoriesList(){
Retrofit retrofit = newsClient.getClient();
apiNews service = retrofit.create(apiNews.class);
Call<List<Category>> call = service.categorriesList();
call.enqueue(new Callback<List<Category>>() {
#Override
public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
if (response.isSuccessful()){
for (int i=0;i<response.body().size();i++){
MenuBurgersFragment pageFragment= new MenuBurgersFragment();
Bundle bundle = new Bundle();
adapter.addFragment(pageFragment, response.body().get(i).getId()+"");
bundle.putString("welcome", response.body().get(i).getId()+"" );
viewPager.setAdapter(adapter);
pageFragment.setArguments(bundle);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onFailure(Call<List<Category>> call, Throwable t) {
Toast.makeText(Tabtest.this, "safsavas", Toast.LENGTH_SHORT).show();
}
});
}
}
ViewPagerAdapter
public 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);
}
}
Fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_menu_list_items, container, false);
bundle = this.getArguments();
if(bundle!=null) {
storeText = bundle.getString("welcome");
Toast.makeText(getContext().getApplicationContext(), storeText, Toast.LENGTH_SHORT).show();
}
In View Pager Bydefault previous and next fragment data is loaded that's why you got next fragment value in toast .
In that you have to set OffscreenPageLimit in viewpager to restrict to load previous and next fragment in View Pager
set value of setOffscreenPageLimit() is 1 .
Hope that above will help you.

Call a method when sliding from one fragment to another

I have 2 Tabs as fragments in a ViewPager in an Activity
When I tap the second tab in the layout, the OnTabUnselected method works.
However, when I slide the screen from one tab to another, the method isn't called.
How do I achieve this calling of method by both means "Tapping as well as in a Sliding Gesture"
My Activity class is:
public class OrderActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private FloatingActionButton printAction;
ViewPagerAdapter adapter;
private Boolean exit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_icon_text_tabs);
TypefaceUtil.overrideFont(getApplicationContext(), "serif", "fonts/opensans.tff");
//TypefaceUtil.overrideFont(getApplicationContext(), "arial", "fonts/opensans.tff");
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
//setupTabIcons();
printAction = (FloatingActionButton) findViewById(R.id.float_print);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Toast.makeText(getApplicationContext(),"onTabSelected",Toast.LENGTH_LONG).show();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
String ac = null;
int pos = viewPager.getCurrentItem();
Fragment activeFragment = adapter.getItem(pos);
if(pos==0){
ac= ((PersonalDetailFragment)activeFragment).getXmlValue();
}
Toast.makeText(getApplicationContext(),ac,Toast.LENGTH_LONG).show();
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
Toast.makeText(getApplicationContext(),"onTabReselected",Toast.LENGTH_LONG).show();
}
});
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new PersonalDetailFragment(), "Personal");
adapter.addFrag(new OrderItemsFragment(), "Invoice");
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 addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Fragment A:
public class FragmentA extends Fragment {
private EditText custName;
public PersonalDetailFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.personal_detail_fragment, container, false);
custName = (EditText) view.findViewById(R.id.customerContactEditText);
return view;
}
public String getXmlValue(){
return custName.getText().toString();
}
}
Fragment B:
public class FragmentB extends Fragment {
private EditText contactNo;
public PersonalDetailFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.personal_detail_fragment, container, false);
contactNo = (EditText) view.findViewById(R.id.customerContactEditText);
return view;
}
}
You can use the ViewPager.addOnPageChangeListener() method to register a listener and get notified about changing the current tab with a pager swipe.
There is a really nice tutorial here.
In your fragment you can use a method named setVisibilityHint that is called every time the visibility of the fragment has been changed. There is a boolean parameter that can be true or false depending if the fragment is visible or not
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}

How to work with ViewPager.OnPageChangeListener

As per this accepted answer, I was able to get my tabLyout as below:
What do I need now, is to be able to change the buttons text based on the fragment position, for example if the position is zero, the Back should not appear, and if the position is the last, the Next should be replaced by Done
I have used the ViewPager.OnPageChangeListener but did not work for me, below is the full code:
public class Slider extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private Button leftBtn, rightBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_up);
leftBtn = (Button) findViewById(R.id.left_btn);
rightBtn= (Button) findViewById(R.id.right_btn);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
// This is not working, even the `Toast` not appearing
private ViewPager.OnPageChangeListener listener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Toast.makeText(Slider.this, "Current position: "+position, Toast.LENGTH_SHORT).show();
if (position == 0) {
leftBtn.setText("");
}
if (position == 3) {
rightBtn.setText("DONE");
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Tab1(),"");
adapter.addFrag(new Tab2(),"");
adapter.addFrag(new Tab3(),"");
adapter.addFrag(new Tab4(),"");
viewPager.setAdapter(adapter);
}
static 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);
}
}
public void next_fragment(View view) {
viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
}
public void previous_fragment(View view) {
viewPager.setCurrentItem(viewPager.getCurrentItem()-1);
}
public void start_app(View view) {
startActivity(new Intent(Slider.this, TrustedNumber.class));
finish();
}
}
It's because you haven't added the listener to the viewpager
viewPager.addOnPageChangeListener(listener);

Dynamic Tab containing List View Showing Adjacent Tab List

I'm having one parent Fragment whose class is Scrollbaltab which contains many dynamic child Fragment whose class is Fragment1 but when I'm scrolling tab "two" it shows tab "one" data and when scroll to tab "three" it shows tab "two" data please help me
//Dynamic Fragment
public class Fragment1 extends Fragment {
RecyclerViewAdapter recyclerViewAdapter;
HashMap<String, ArrayList<String>> item = new HashMap<String,ArrayList<String>>();
ArrayList onlineData1 = new ArrayList<>();
ArrayList onlineData2 = new ArrayList<>();
ArrayList onlineData3 = new ArrayList<>();
String titleName="";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflateView = inflater.inflate(R.layout.fragment_fragment1, null, false);
RecyclerView recyclerView = (RecyclerView) inflateView.findViewById(R.id.recyclerView);
recyclerView.removeAllViews();
recyclerViewAdapter = new RecyclerViewAdapter(this.getActivity() ,item.get(titleName));
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.notifyDataSetChanged();
recyclerView.setHasFixedSize(true);
//Layout manager for Recycler view
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity() ));
recyclerViewAdapter.notifyDataSetChanged();
return inflateView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int tab_position = Scrollbaltab.pos;
if(onlineData1.isEmpty())
{
onlineData1.clear();
}
if(onlineData2.isEmpty())
{
onlineData2.clear();
}
if(onlineData3.isEmpty())
{
onlineData3.clear();
}
item.clear();
onlineData1.add("one");
onlineData1.add("two");
onlineData1.add("three");
onlineData2.add("a");
onlineData2.add("b");
onlineData2.add("c");
onlineData3.add("x");
onlineData3.add("y");
onlineData3.add("z");
if(item.get("ONE")==null)
item.put("ONE",onlineData1);
if(item.get("TWO")==null)
item.put("TWO",onlineData2);
if(item.get("THREE")==null)
item.put("THREE",onlineData3);
String [] arr= new String[]{"ONE","TWO","THREE"};
if(tab_position>=0) {
titleName = arr[tab_position];
}
// set adpter
Log.d("values"+tab_position,item.get(titleName).toString());
}
}
//parent Fragment
public class Scrollbaltab extends AppCompatActivity {
Toolbar toolbar;
ViewPager viewPager;
TabLayout tabLayout;
ViewPagerAdapter adapter;
public static int pos=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrollbaltab);
inlizeview();
}
private void inlizeview() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("scrolling tabbar");
setSupportActionBar(toolbar);
//both are use for set arrow back button in toolbar
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
// when click on arrow button of tootbar it finish the current activity
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
pos=position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Fragment1(), "ONE");
adapter.addFragment(new Fragment1(), "TWO");
adapter.addFragment(new Fragment1(), "THREE");
viewPager.setAdapter(adapter);
}
}
//view pager adapter
public final List<Fragment> mFragmentList = new ArrayList<>();
public final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
Log.e("DD","mFragmentList--"+mFragmentList.get(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);
}
#Override
public int getItemPosition(Object object){
return ViewPagerAdapter.POSITION_NONE;
}
}

Catch the changing of slide in a ViewPager

I have implemented a ViewPager in order to swipe between two Fragments like such:
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.statistics_general_vp, container, false);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
mStatisticsPagerAdapter = new StatisticsPagerAdapter(getActivity().getSupportFragmentManager());
mViewPager.setAdapter(mStatisticsPagerAdapter);
return view;
}
public class StatisticsPagerAdapter extends FragmentStatePagerAdapter {
public StatisticsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return new GeneralStatistics();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
But for now my two slides display the same Fragment.
How may I have slide 1 display Fragment 1 and slide 2 Fragment 2?
have u created fragment1 and fragment 2 seperately?? if yes then do this - in activity holding these two fragments.
private void createViewPager(ViewPager viewPager) {
Log.d("activity", "viewpager");
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Fragment1(), "");
adapter.addFrag(new Fragment2(), "");
viewPager.setAdapter(adapter);
}
create fragment like this -
public class Fragment1 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.transaction_layout, container, false);
return v;
}
}
create viewpager like this -
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);
}
}
or if you want to make tab with icons use this method -
private void createTabIcons() {
Log.d("activity", "createtabicons");
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.tab_item2, null);
tabOne.setText("QR Scan");
tabOne.setTypeface(MRR);
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.image1, 0, 0);
tabOne.setCompoundDrawablePadding(5);
tabLayout.getTabAt(0).setCustomView(tabOne);
tabLayout.getTabAt(0).getCustomView().setSelected(true);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.tab_item2, null);
tabTwo.setText("Mobile No.");
tabTwo.setTypeface(MRR);
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.image3, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
tabTwo.setCompoundDrawablePadding(5);
}
Hello i show you what i doing, i got 2 fragments in mainActivity
private void addFragments() {
List<Fragment> fragments = new ArrayList<>();
chatFragment = new ChatFragment();
remoteFragment = new RemoteFragment();
fragments.add(remoteFragment);
fragments.add(chatFragment);
MyPageAdapter adapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(TAB_REMOTE_POSITION)
.setIcon(getDrawable(R.drawable.ic_settings_remote_white_24dp));
tabLayout.getTabAt(TAB_SOCIAL_POSITION)
.setIcon(getDrawable(R.drawable.ic_group_white_24dp));
}
Here is my adapter:
class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
and on OnCreate u should
addFragments();
also i bind the views with ButterKnife
#Bind(R.id.view_pager)
ViewPager viewPager;
#Bind(R.id.tab_layout)
TabLayout tabLayout;
but u can static implement this with android
And remember that u have listeners:
private void pageChangeListener() {
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService
(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
});
}

Categories

Resources