I'm starting with some Design support Library resources, specifically the TabLayout.
It's a simple snippet, but I'm not able to populate my TabLayout, the Fragments are sliding normally but my TabLayout is not getting populatad with the Titles as we can see in the attached picture.
I'm not sure if I should wrap ViewPager inside a fragment together with the TabLayout, it just make sense to me.
Follow, thanks.
http://postimg.org/image/x1z6zvlqd/
Main fragment Xml
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tab_sliding_tabs_about"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
android:background="#color/yellow"
/>
<android.support.v4.view.ViewPager
android:id="#+id/vp_about_fragment_content"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
Main fragment java
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about, container, false);
ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.vp_about_fragment_content);
mAdapter = new AboutPageAdapter(getFragmentManager(),
getContext());
viewPager.setAdapter(mAdapter);
TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tab_sliding_tabs_about);
tabLayout.setupWithViewPager(viewPager);
mAdapter.notifyDataSetChanged();
return rootView;
}
Page Adapter java
public class AboutPageAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
private String tabTitles[] = new String[]{"Tab A", "Tab B"};
private Context context;
public AboutPageAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragA.newInstance(position);
default:
return FragB.newInstance(position);
}
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
Thanks for all your tips, I was able to make it work with:
mViewPager.setAdapter(adapter);
mTabLayout.post(new Runnable() {
#Override
public void run() {
mTabLayout.setupWithViewPager(mViewPager);
}
});
"Official" Workaround:
https://code.google.com/p/android/issues/detail?id=180462#c17
if (ViewCompat.isLaidOut(tabLayout)) {
tabLayout.setupWithViewPager(viewPager);
} else {
tabLayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
tabLayout.setupWithViewPager(viewPager);
tabLayout.removeOnLayoutChangeListener(this);
}
});
}
Related
I am not that experienced in Java so I can't figure it out myself.
I bought a template with a tablayout which looks like this (image 1):
I want to disable the swipe function between these two tabs, so it should only be possible to get to "TAB 2" by clicking on the tab "TAB 2".
There are a lot of tutorials in the Internet but non of them fits to my code so I'm a bit confused.
Here is my TabFragment:
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
if(position == 0){
return new Tab1();
}
if(position == 1){
return new Tab2();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Tab 1";
case 1 :
return "Tab 2";
}
return null;
}
}}
and my tab_layout.xml
<?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"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:tabGravity="fill"
app:tabMode="fixed"
android:background="#color/material_blue_grey_800"
app:tabIndicatorColor="#color/orange"
app:tabSelectedTextColor="#color/orange"
app:tabTextColor="#color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="50dp">
</android.support.v4.view.ViewPager>
</LinearLayout>
I tried my best to figure out how to solve it but didn't succeed, so I hope one of you can help me with this small problem :)
Thanks a lot.
You need to create a custom ViewPager that intercepts the onTouch events and avoid the default behaviour. This way the user wont be able to swipe between pages but will be able to touch on the tabs.
You can check this link where is already answered: How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?
EDIT
I'll explain it by steps:
Create a new class called NonSwipeableViewPager
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;
import java.lang.reflect.Field;
public class NonSwipeableViewPager extends ViewPager {
public NonSwipeableViewPager(Context context) {
super(context);
setMyScroller();
}
public NonSwipeableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
setMyScroller();
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
//down one is added for smooth scrolling
private void setMyScroller() {
try {
Class<?> viewpager = ViewPager.class;
Field scroller = viewpager.getDeclaredField("mScroller");
scroller.setAccessible(true);
scroller.set(this, new MyScroller(getContext()));
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyScroller extends Scroller {
public MyScroller(Context context) {
super(context, new DecelerateInterpolator());
}
#Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
super.startScroll(startX, startY, dx, dy, 350 /*1 secs*/);
}
}
}
Modify your layout to use the new ViewPager
<?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"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:tabGravity="fill"
app:tabMode="fixed"
android:background="#color/material_blue_grey_800"
app:tabIndicatorColor="#color/orange"
app:tabSelectedTextColor="#color/orange"
app:tabTextColor="#color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TabLayout>
<NonSwipeableViewPager <!-- You will need to import this correctly with your class package -->
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="50dp">
</NonSwipeableViewPager>
</LinearLayout>
Update your activity with the new ViewPager
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static NonSwipeableViewPager viewPager; // This line changed
public static int int_items = 2 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (NonSwipeableViewPager) x.findViewById(R.id.viewpager); // This line changed
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
You can keep the same adapter MyAdapter.
This will avoid the swipe between tabs but will keep the click on each one.
I know this is quite old but you need to switch to ViewPager2.
ViewPager2 replaces androidx.viewpager.widget.ViewPager, addressing most of its predecessor’s pain-points, including right-to-left layout support, vertical orientation, modifiable Fragment collections, etc.
If you need to disable user swipe support then you can call:
viewPager2.isUserInputEnabled = false
I use ViewPager to create fragments that swipe left and now I want insert fragments into each fragment page.
activityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
...
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/myviewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<devlight.io.library.ntb.NavigationTabBar
android:id="#+id/ntb_horizontal"
app:ntb_swiped="true"/>
</android.support.design.widget.CoordinatorLayout>
and this:
tab0_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:textSize="30sp"
android:gravity="center"
android:id="#+id/textView"
android:layout_centerHorizontal="true"
android:textColor="#android:color/holo_green_dark"
android:text="Social\nFragment"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:textSize="15sp"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:text="androidbelieve.com"
android:textColor="#000"
android:layout_below="#+id/textView"
android:textStyle="italic"/>
</RelativeLayout>
I have a ViewPager in mainActivity.java
final ViewPager viewPager = (ViewPager) findViewById(R.id.myviewpager);
viewPager.setAdapter(new PagerAdapter() {
...
...
}
I try open one screen in viewpager via fragment layout.
I try this:
final ViewPager viewPager = (ViewPager) findViewById(R.id.myviewpager);
viewPager.setAdapter(new PagerAdapter() {
...
public Object instantiateItem(final ViewGroup container, final int position) {
if (position == 0)
{
final View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.fragment_tab0, null, false);
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.myviewpager,new tab0Fragment()).commit();
container.addView(view);
return view;
}
else if (position == 1)
...
}
...
}
AND tab0Fragment.java
public class tab0Fragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tab0,null);
}
}
I am noob in android. how can correct this code?
Solution:
The answers was not my answer but that help me a lot.
According #Mr. Rabbit ans #Amit Upadhyay I change top code to this:
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
if (position == 0)
{
final View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.fragment_tab0, null, false);
MyAdapter adapter = new MyAdapter(getSupportFragmentManager());
adapter.addFragment(new tab0Fragment(), getResources().getString(R.string.tab0));
container.addView(view);
return view;
}
else if (position == 1)
{
and also adding MyAdapter class according #Mr. Rabbit's answer.
hope help someone else.
Try to separate out your adapter and below code.
MyAdapter.java
public class MyAdapter extends FragmentPagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public MyAdapter(FragmentManager fm) {
super(fm);
}
#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);
}
}
Create your Fragments
FragmentOne.java
public class FragmentOne extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
}
FragmentTwo.java
public class FragmentTwo extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
return view;
}
}
Setup your viewpager like this in your activity.
final ViewPager viewPager = (ViewPager) findViewById(R.id.myviewpager);
MyAdapter adapter = new MyAdapter(getSupportFragmentManager());
// Add your fragments in adapter.
FragmentOne fragmentOne = new FragmentOne();
adapter.addFragment(fragmentOne, getResources().getString(R.string.fragment_one_title));
FragmentTwo fragmentTwo = new FragmentTwo();
adapter.addFragment(fragmentTwo, getResources().getString(R.string.fragment_two_title));
viewPager.setAdapter(adapter);
Then finally set your NavigationTabBar with your ViewPager.
final NavigationTabBar navigationTabBar = (NavigationTabBar) findViewById(R.id.ntb_horizontal);
navigationTabBar.setViewPager(viewPager, 2);
To achieve this you can create a custom ViewPagerAdapter. Eg:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
/**
* Created by aupadhyay on 1/5/17.
*/
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
public void addFragments(Fragment fragment, String tabTitle)
{
this.fragments.add(fragment);
this.tabTitles.add(tabTitle);
}
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
}
Now you can set adapter on viewpager like this:
final ViewPager viewPager = (ViewPager) findViewById(R.id.myviewpager);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new Tab0Fragment(), "First");
viewPagerAdapter.addFragments(new Tab1Fragment(), "Second");
viewPagerAdapter.addFragments(new Tab2Fragment(), "Third");
// add more if required.
viewPager.setAdapter(viewPagerAdapter);
Tab0Fragment, Tab1Fragment, Tab1Fragment are the fragments created by you to add in your viewpager.
EDIT: I have tried to find textView under bad View.
I have activity with tabView which contains two tabs. For each tab i want to have different layout. How can i initiate my element from each view? I´m trying to do that from my activity but when i´m searching for my element it returns null. Here is my code with only one tab.
My activity.
public class MyTariffListActivity extends AppCompatActivity {
TextView tariffName;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_view_layout);
tariffName = (TextView) findViewById(R.id.tariffName);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Basic Info"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PageAdapterTariff adapter = new PageAdapterTariff
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
Tariff tariff = getIntent().getParcelableExtra(MyCommonListActivity.TARIFF);
tariffName.setText(tariff.getName()); // HERE tariffName is null
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
My pageAdapter
public class PageAdapterTariff extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PageAdapterTariff(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TariffInfoTab tariffInfoTab = new TariffInfoTab();
return tariffInfoTab;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
My tab definition:
public class TariffInfoTab extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_my_show_tariff, container, false);
}
}
My activity_my_show_tariff layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:id="#+id/tariffName"
android:gravity="center"
android:layout_span="3"
android:padding="3dip" />
</RelativeLayout>
Refer this. It will help you.
android-material-design-working-with-tabs
I have a fragment alertsfragment.java , which has a grid view layout, when I open that , it works normally , but as soon I swipe between other tabs ,it vanishes away .
to explain more , I have an activity tab layout which has a tab on the bottom , and its first tab opens two fragments alertsfragment and friendsfragment,
I am including the code and the screenshot for simplification.
staring with mapfragment which contains two fragment alert frag and friends frag
mapfragment.java
public class MapFragment extends Fragment{
TabLayout tabLayout;
ViewPager viewPager;
public MapFragment()
{
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View ROOTView =inflater.inflate(R.layout.mapfragment,container,false);
viewPager = (ViewPager)ROOTView.findViewById(R.id.viewpager2);
setupViewPager(viewPager);
tabLayout = (TabLayout)ROOTView.findViewById(R.id.tabs);
//viewPager.setOffscreenPageLimit(2);
tabLayout.setupWithViewPager(viewPager);
return ROOTView;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(this.getFragmentManager());
adapter.addFragment(new FriendsFragment(), "FRIENDS");
adapter.addFragment(new AlertsFragment(), "Alerts");
setRetainInstance(true);
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);
}
}
}
alertsfragment.java
public class AlertsFragment extends Fragment{
GridView grid;
final String[] name = {
"Google",
"Github",
"Instagram",
"Facebook",
} ;
final String[] status = {
"Google",
"Github",
"Instagram",
"Facebook",
} ;
final String[] place = {
"Google",
"Github",
"Instagram",
"Facebook",
} ;
final int[] imageId = {
R.drawable.logo,
R.drawable.logo,
R.drawable.logo,
R.drawable.logo,
};
public AlertsFragment()
{
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View alertsfrag =inflater.inflate(R.layout.alertsfragments,container,false);
grid=(GridView) alertsfrag.findViewById(R.id.grid);
CustomGrid adapter = new CustomGrid(getActivity(), name,status,place,imageId);
grid=(GridView)alertsfrag.findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "You Clicked at " +name[+ position], Toast.LENGTH_SHORT).show();
}
});
return alertsfrag;
}
}
its customadapter
public class CustomGrid extends BaseAdapter{
private Context mContext;
private final String[] name;
private final String[] status;
private final String[] place;
private final int[] Imageid;
public CustomGrid(Context c,String[] name,String[] status,String[] place,int[] Imageid ) {
mContext = c;
this.Imageid = Imageid;
this.name = name;
this.status = status;
this.place = place;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name.length;
// return status.length;
// return place.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
TextView textView1 = (TextView) grid.findViewById(R.id.grid_text1);
TextView textView2 = (TextView) grid.findViewById(R.id.grid_text2);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
textView.setText(name[position]);
textView1.setText(status[position]);
textView2.setText(place[position]);
imageView.setImageResource(Imageid[position]);
} else {
grid = (View) convertView;
}
return grid;
}
}
its XML
alertsfrag.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AlertsFragment" >
<GridView
android:layout_marginTop="60dp"
android:numColumns="2"
android:gravity="center"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/grid"
/>
</LinearLayout>
mainTabLayout
TabLayout.java
public class Bottom_Tabs_Activity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_friends,
R.drawable.ic_map,
R.drawable.ic_status,
R.drawable.ic_chat,
R.drawable.ic_profile
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs);
viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null)
setupViewPager(viewPager);
else {
Log.e("test", "i am null");
}
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
tabLayout.getTabAt(4).setIcon(tabIcons[4]);
}
private void setupViewPager(ViewPager viewPager)
{
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new MapFragment(),"MAPS");
adapter.addFrag(new PeopleFragment(),"PEOPLE");
adapter.addFrag(new HomeFragment(),"HOME");
adapter.addFrag(new ChatFragment(),"CHAT");
adapter.addFrag(new ProfileFragment(),"PROFILE");
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 null to display only the icon
return null;
}
}
}
TabLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:orientation="vertical"
android:weightSum="1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".9"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:tabMode="fixed"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".1"
android:background="#000000"
app:tabIndicatorColor="#ff1232"
app:tabGravity="fill"
/>
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_gravity="bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
</android.support.design.widget.AppBarLayout>
</LinearLayout>
</LinearLayout>
Screenshots
Before and after
any kind of help would be appreciated:)
needed to use getChildFragmentManager() instead of getFragmentManager() for placing and managing Fragments inside of a Fragment.
see mapfragment.java , there I used this and the problem got solved
Do not use FragmentPagerAdapter.
you have to use FragmentStatePagerAdapter on ViewPagerAdapter Class.
class ViewPagerAdapter extends FragmentStatePagerAdapter
{
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 null to display only the icon
return null;
}
}
I am trying to pass an object that is retrieved and created during my main activities on create method to one of the fragments of my sliding tabs layout.
Since this object is created over a network connection my plan was to receive the data during the creation of the Main Activity then pass the resulting object to my fragments. However this seems easier said than done. The resulting object will then get passed to a recycler view in the Forecast fragment.
I have read various methods including implementing the parcelable interface on my model object, storing it as a bundle and trying to send it over to the fragment. However it always came up null. I believe this was due to me creating a new fragment in memory and not passing the bundle to the fragment that was displayed. I also don't have any ID's for the fragments so locating them by ID isn't possible, at least to my knowledge.
If anyone could point me in the right direction Id be greatly appreciative.
Main Activity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MAIN ACTIVITY";
#Bind(R.id.toolBar) Toolbar mToolbar;
#Bind(R.id.viewPager) ViewPager mViewPager;
#Bind(R.id.tabLayout) SlidingTabLayout mTabLayout;
private ViewPagerAdapter mAdapter;
private String mForecastsTabName = "Forecasts";
private String mAlertsTabName = "Alerts";
private String mTabTitles[] = {mForecastsTabName, mAlertsTabName};
private int mNumberOfTabs = 2;
private Forecast[] mForecasts;
private JsonParser mJsonParser = new JsonParser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
setupSlidingTabs();
}
private void setupSlidingTabs() {
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
mAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mTabTitles, mNumberOfTabs);
// Assigning the ViewPages View and setting the adapter
mViewPager.setAdapter(mAdapter);
// Assigning the Sliding Tab Layout View
mTabLayout.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
mTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.ColorAccent);
}
});
mTabLayout.setViewPager(mViewPager);
}
Forecast Fragment.java
public class ForecastFragment extends Fragment {
private static final String FORECAST_KEY = "FORECAST_KEY";
private static final String TAG = "FRAGMENT";
private Forecast[] mForecasts;
#Bind(R.id.recyclerView) RecyclerView mRecyclerView;
#Bind(R.id.emptyView) TextView mEmptyView;
#Bind(R.id.locationButton) Button mLocationButton;
public static ForecastFragment newInstance(Forecast[] forecasts) {
ForecastFragment fragment = new ForecastFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArray(FORECAST_KEY, forecasts);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize dataset, this data would usually come from a local content provider or
// remote server.
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.forecast_tab_fragment, container, false);
ButterKnife.bind(this, view);
displayEmptyViewIfNoData();
ForecastAdapter adapter = new ForecastAdapter(getActivity(), mForecasts);
mRecyclerView.setAdapter(adapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(layoutManager);
return view;
}
private void displayEmptyViewIfNoData() {
if (mForecasts == null || mForecasts.length < 1) {
mRecyclerView.setVisibility(View.GONE);
mEmptyView.setVisibility(View.VISIBLE);
mLocationButton.setVisibility(View.VISIBLE);
}
else {
mRecyclerView.setVisibility(View.VISIBLE);
mEmptyView.setVisibility(View.GONE);
mLocationButton.setVisibility(View.GONE);
}
}
#OnClick(R.id.locationButton)
public void selectLocations(View view) {
Intent intent = new Intent(getActivity(), LocationSelectionActivity.class);
intent.putExtra(ActivityConstants.CALLING_ACTIVITY, ActivityConstants.FORECAST_ACTIVITY);
startActivity(intent);
}
}
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
// This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
String mTitles[];
// Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
int mNumberOfTabs;
SparseArray<Fragment> registeredFragments = new SparseArray<>();
public ViewPagerAdapter(FragmentManager fm, String titles[], int numberOfTabs) {
super(fm);
mTitles = titles;
mNumberOfTabs = numberOfTabs;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if (position == 0) {
ForecastFragment forecastFragment = new ForecastFragment();
return forecastFragment;
}
else if (position == 1) {
AlertFragment alertFragment = new AlertFragment();
return alertFragment;
}
return null;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return mTitles[position];
}
#Override
public int getCount() {
return mNumberOfTabs;
}
}
Forecast_tab_fragment.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/ColorPrimaryLight">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/activity_vertical_margin"/>
<TextView
android:id="#+id/emptyView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/empty_forecast_message"
android:textColor="#color/ColorTextPrimary"
android:gravity="center"
android:visibility="gone"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="115dp"/>
<Button
android:id="#+id/locationButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/button_shape"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:textColor="#color/ColorTextPrimary"
android:text="#string/add_forecast_button"
android:visibility="gone"
android:layout_alignParentBottom="false"
android:layout_centerHorizontal="true"
android:layout_below="#+id/emptyView"
android:layout_marginTop="24dp"/>
</RelativeLayout>
When you do this code below, you can hand the data to your fragment.
In your Activity, call below, when the data is ready:
mAdapter.getFragment(index).setData(dataObject);
or
mAdapter.getFragment(mViewPager.getCurrentItem()).setData(dataObject);
Your FragmentPagerAdater should be like this:
class CustomPagerAdapter extends FragmentPagerAdapter {
SparseArray<App4StoreBaseSubFragment> registeredFragments = new SparseArray<App4StoreBaseSubFragment>();
public CustomPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
App4StoreBaseSubFragment fragment = (App4StoreBaseSubFragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public ForecastFragment getFragment(int position){
return registeredFragments.get(position);
}
}
Your Fragment should be like this:
public class ForecastFragment extends Fragment {
public void setData(Forecast forecast){
//write code here to change UI
}
}