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
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.
I have got some weird problem after implementing multiple instance(loaded dynamically depending on the data) of same fragment inside a Viewpager.
My fragment class consists of a listview which will be populated according to the data retrieved from the server, but every time i swipe page from one to another, the data inside a listview of the fragment is jumbled.
Here is the code. Any help will be appreciated. Thank You.
This the Fragment class where the Viewpager is present.
public class Menu extends Fragment implements View.OnClickListener {
private SlidingTabLayout mSlidingTab;
SlidingUpPanelLayout mLayout;
private ArrayList<String> menu_names;
private ViewPager pager;
ActionBarActivity act;
public ArrayList<ArrayList<All_Data>> menus;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.main, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
mSlidingTab = (SlidingTabLayout) act.findViewById(R.id.sliding_tab);
mSlidingTab.setDistributeEvenly(true);
mSlidingTab.setCustomTabView(R.layout.custom_text, 0);
pager= (ViewPager) act.findViewById(R.id.pager);
mSlidingTab.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return android.R.color.transparent;
}
});
mSlidingTab.bringToFront();
menuUpdate();
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return Meals.newInstance(position);
}
#Override
public int getCount() {
return menu_names.size();
}
#Override
public CharSequence getPageTitle(int i) {
return menu_names.get(i);
}
}
private void menuUpdate(String result) {
//menu_names= List Retrieved from server
//menus= List Retrieved from server
pager.setAdapter(new MyPagerAdapter(act.getSupportFragmentManager()));
mSlidingTab.setViewPager(pager);
}
Meals.java(Fragment class):
public class Meals extends Fragment {
ActionBarActivity activity;
int position = 0;
static Meals newInstance(int page) {
Meals fragmentFirst = new Meals();
Bundle args = new Bundle();
args.putInt("position", page);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.meals, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
position = getArguments().getInt("position");
ArrayList<All_Data> mMeals;
Fragment menu = activity.getSupportFragmentManager().findFragmentByTag("Menu");
mMeals = ((Menu) menu).menus.valueAt(position);
ListView mList = (ListView) activity.findViewById(R.id.mainMenu1);
LayoutInflater inflater;
inflater = LayoutInflater.from(activity.getApplicationContext());
mList.addHeaderView(inflater.inflate(R.layout.custom_text, mList, false));
mList.addFooterView(inflater.inflate(R.layout.footer, mList, false));
Menu_adapter adapter = new Menu_adapter(((Menu) menu), mMeals, activity);
mList.setAdapter(adapter);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (ActionBarActivity) context;
}
#Override
public void onResume() {
super.onResume();
MyApplication.getInstance().trackScreenView("Startes Screen");
}
}
meals.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="#f1f2f3"
android:orientation="vertical">
<ListView
android:id="#+id/mainMenu1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#f1f2f3"
android:dividerHeight="20dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:scrollbars="none" />
</RelativeLayout>
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'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);
}
});
}