I want to set up different content in every tab. I'm new to android. How can I change code so it would be easy to manage content of every tab?
that what I have:
The problem is that I have the same content at each tab.
Here's MainActivity:
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener
{
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Here we load the xml layout we created above
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
{
#Override
public void onPageSelected(int position)
{
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++)
{
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
Rest of code is inner within MainActivity:
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
Class SectionPagerAdapter:
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return new PlaceholderFragment();
}
#Override
public int getCount()
{
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position)
{
Locale l = Locale.getDefault();
switch (position)
{
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
PlaceholderFragment contains gridview:
public class PlaceholderFragment extends Fragment
{
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Here we inflate the layout we created above
GridView gridView = (GridView) rootView.findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(MainActivity.this.getApplicationContext()));
return rootView;
}
}
and MyAdapter where I added items to content:
private class MyAdapter extends BaseAdapter
{
private List<Item> items = new ArrayList<Item>();
private LayoutInflater inflater;
public MyAdapter(Context context)
{
inflater = LayoutInflater.from(context);
items.add(new Item("APO Supreme", R.drawable.snb_apo_supreme));
items.add(new Item("Arbor Blacklist", R.drawable.snb_arbor_blacklist));
items.add(new Item("Arbor Draft", R.drawable.snb_arbor_draft));
items.add(new Item("Arbor Relapse", R.drawable.snb_arbor_relapse));
items.add(new Item("Capita Defenders of Awesome", R.drawable.snb_capita_defenders_of_awesome));
items.add(new Item("Capita Outsiders", R.drawable.snb_capita_outsiders));
items.add(new Item("Capita Ultrafear", R.drawable.snb_capita_ultrafear));
items.add(new Item("DC Focus", R.drawable.snb_dc_focus));
items.add(new Item("DC Mega", R.drawable.snb_dc_mega));
items.add(new Item("DC Tone", R.drawable.snb_dc_tone));
items.add(new Item("ROME Agent", R.drawable.snb_rome_agent));
items.add(new Item("ROME Agent Rocker", R.drawable.snb_rome_agent_rocker));
items.add(new Item("ROME Hammerhead", R.drawable.snb_rome_hammerhead));
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i)
{
return items.get(i);
}
#Override
public long getItemId(int i)
{
return items.get(i).picId;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup)
{
View v = view;
ImageView picture;
TextView name;
if(v == null)
{
v = inflater.inflate(R.layout.gridview_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);
Item item = (Item)getItem(i);
picture.setImageResource(item.picId);
name.setText(item.name);
return v;
}
private class Item
{
final String name;
final int picId;
Item(String name, int drawableId)
{
this.name = name;
this.picId = drawableId;
}
}
}
I know its quite messy and a lot of code so here's folder with project
P.S. I'm working in Android Studio
Thanks for help
I think your problem is
#Override
public Fragment getItem(int position)
{
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return new PlaceholderFragment();
}
ViewPager must to return different fragments from each page item.
Create three fragments and use the same layout for each.
Then put this fragments into ArrayList and return fragment that you need in getItem method depends of position number.
EDIT:
Example:
private List<Fragment> mFragments = new Vector<Fragment>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_fragment_activity_layout);
mFragments.add(new FirstFragment());
mFragments.add(new SecondFragment());
...
...
}
In your SectionsPagerAdapter use
#Override
public Fragment getItem(int position)
{
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return mFragments.get(position);
}
Then in FirstFragment and SecondFragment and other fragments use R.layout.activity_main
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
GridView gridView = (GridView) v.findViewById(R.id.gridview);
return v;
}
And now in onResume() method in every fragment use different custom content in adapter
public void onResume(){
gridView.setAdapter(new MyAdapter(getActivity()));
}
You should use custom adapter for each gridView to show different information or you can pass to adapter different content. Read more about adapters and how to pass data content into it.
Related
I'm using swipeable tabs as part of an activity with a total of 3 sections. I'm providing the right and left arrows to navigate to the other sections of the swipe-view.
I want my left arrow to disappear when I'm at the leftmost section and my right-arrow to disappear when I'm at the rightmost section.
Here's what I'm trying rightnow, but not getting the desired result:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
static Button rightButton;
static Button leftButton;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rightButton = (Button)findViewById(R.id.buttonRight);
leftButton = (Button)findViewById(R.id.buttonLeft);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
// Returns a new instance of this fragment for the given section number.
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
String text = instructions(sectionNumber);
textView.setText(text);
return rootView;
}
private String instructions(int sectionNumber) {
if (sectionNumber == 1) {
leftButton.setVisibility(View.INVISIBLE);
rightButton.setVisibility(View.VISIBLE);
Log.i("Welcome"," to section 1");
return "All questions are mandatory. Each question carries 1 mark. There is no negative marking";
}
else if(sectionNumber == 2) {
leftButton.setVisibility(View.VISIBLE);
rightButton.setVisibility(View.VISIBLE);
Log.i("Welcome", " to section 2");
return "Color the bubble besides the option you think is best for the answer.";
}
else {
leftButton.setVisibility(View.VISIBLE);
rightButton.setVisibility(View.INVISIBLE);
Log.i("Welcome", " to section 3");
return "Click on the skip button above to start the test. Timer will start as soon as you'll click that button!";
}
}
}
}
As you can see in the method instructions, I tried using logs to see what's happening only to find that I never get the "Welcome to section 2" part even after swiping through the tabs multiple times. Although, the texts related to a given section are returned correctly. What am I missing here?
The problem is that you returned a new fragment in getItem
Do it like this:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<Fragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
mFragments.add(PlaceholderFragment.newInstance(1));
mFragments.add(PlaceholderFragment.newInstance(2));
mFragments.add(PlaceholderFragment.newInstance(3));
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
}
Also change the Buttons to the fragment_main layout "not" in activity_main and use it like this.
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private Button rightButton;
private Button leftButton;
// Returns a new instance of this fragment for the given section number.
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
rightButton = (Button)rootView.findViewById(R.id.buttonRight);
leftButton = (Button)rootView.findViewById(R.id.buttonLeft);
int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
String text = instructions(sectionNumber);
textView.setText(text);
return rootView;
}
EDIT if you want to know the cuurent page you have to implement this.
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.i("Welcome", "page "+ position+1);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Also add the following line so that the system will create your fragment only once:
mViewPager.setOffscreenPageLimit(3);
The issue you had is that you're getting the position that the system created now not the current page.
I am working in a new Android project.
The first activity is using a slider menu and fragments. On the first fragment there is a list view (PrimaryFragmentDormir.java). After selecting one of the rows, a new activity is launched. This last activity uses three tabs, to show different information about the selected row object.
The listview is loaded from remote JSON files.
This is the onItemClick method at PrimaryFragmentDormir.java:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Hotel hotelActual = (Hotel) adapter.getItem(position);
String msg = "Elegiste el hotel " + hotelActual.getNombre();
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), Detalle_Hotel.class);
intent.putExtra("id_hotel", hotelActual.getId_hotel());
intent.putExtra("nombre_hotel", hotelActual.getId_hotel());
intent.putExtra("descripcion_hotel", hotelActual.getId_hotel());
intent.putExtra("latitud_hotel", hotelActual.getId_hotel());
intent.putExtra("longitud_hotel", hotelActual.getId_hotel());
intent.putExtra("direccion_hotel", hotelActual.getId_hotel());
intent.putExtra("web_hotel", hotelActual.getId_hotel());
intent.putExtra("tel_hotel", hotelActual.getId_hotel());
intent.putExtra("tel_reservas", hotelActual.getId_hotel());
intent.putExtra("foto_hotel", hotelActual.getId_hotel());
intent.putExtra("calificacion_hotel", hotelActual.getId_hotel());
intent.putExtra("num_estrellas", hotelActual.getId_hotel());
intent.putExtra("zona_hotel", hotelActual.getId_hotel());
intent.putExtra("facebook_hotel", hotelActual.getFacebook());
intent.putExtra("twitter_hotel", hotelActual.getTwitter());
startActivity(intent);
}
The Toast is shown and the activity Detalle_Hotel is shown also.
Detalle_Hotel has three tabs.
What I need is to get the values from hotelActual in the three tabs, in order to work with them separately.
This is Detalle_Hotel activity:
public class Detalle_Hotel extends AppCompatActivity {
// Declaring Your View and Variables
private String nombre_hotel, foto_hotel, descripcion_hotel,direccion_hotel,web_hotel,tel_hotel,tel_reservas,zona_hotel,facebook_hotel,twitter_hotel;
private int num_estrellas_hotel, id_hotel;
private double calificacion_hotel,latitud_hotel,longitud_hotel;
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Info","Mapa","OpiniĆ³n"};
int Numboftabs =3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detalle__hotel);
nombre_hotel = getIntent().getStringExtra("nombre_hotel");
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.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
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.rojomodesto);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
}
Here I received the value from nombre_hotel (as test for the other values), and now how can I pass it to the tabs?
Here is tab1 code:
public class Tab1 extends Fragment {
private TextView hotel_nombre;
private String nombre_hotel;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
return v;
}
#Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
hotel_nombre = (TextView) getView().findViewById(R.id.nombre_hotel);
hotel_nombre.setText(getActivity().nombre_hotel));
}
}
The line hotel_nombre.setText(getActivity().nombre_hotel)); shows a warning at the second nombre_hotel: "Cannot resolve symbol 'nombre_hotel'.
Any help is welcome.
EDIT:
ViewPageAdapter.java
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm, CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if (position == 0) // if the position is 0 we are returning the First tab
{
Tab1 tab1 = new Tab1();
return tab1;
}
if (position == 1) // if the position is 0 we are returning the First tab
{
Tab2 tab2 = new Tab2();
return tab2;
}
if (position == 2) // if the position is 0 we are returning the First tab
{
Tab3 tab3 = new Tab3();
return tab3;
}
return null;
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
In your adapter you need to initialize it properly now (with string as argument).
public class Tab1 extends Fragment {
private static final String HOTEL = "hotel";
private TextView hotel_nombre;
private String nombre_hotel;
public static Tab1 newInstance(String s) {
Tab1 result = new Tab1();
Bundle bundle = new Bundle();
bundle.putString(HOTEL, s);
result.setArguments(bundle);
return result;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
nombre_hotel = bundle.getString(HOTEL);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
return v;
}
#Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
hotel_nombre = (TextView) getView().findViewById(R.id.nombre_hotel);
hotel_nombre.setText(nombre_hotel);
}
}
EDIT:
Change your in your Detalle_Hotel Activity, adapter to:
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs,nombre_hotel);
And then in adapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
private String hotelNumbre;
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm, CharSequence mTitles[], int mNumbOfTabsumb, String hotelNum) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
this.hotelNumbre = hotelNum;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if (position == 0) // if the position is 0 we are returning the First tab
{
return Tab1.newInstance(hotelNumbre);
}
if (position == 1) // if the position is 0 we are returning the First tab
{
Tab2 tab2 = new Tab2();
return tab2;
}
if (position == 2) // if the position is 0 we are returning the First tab
{
Tab3 tab3 = new Tab3();
return tab3;
}
return null;
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
You need to make nombre_hotel field public instead of private, then use:
hotel_nombre.setText((Detalle_Hotel)getActivity().nombre_hotel));
val intent = Intent(activity, VoiceCommandServiceActivity::class.java)
intent.putExtra(SELECT_SERVICES, mServiceName as Serializable)
startActivity(activity, intent)
intent?.let {
it.extras?.let { extras ->
extras?.let { bundle ->
if (bundle.containsKey(SELECT_SERVICES)) {
val service = extras.getSerializable(SELECT_SERVICES) as MutableList<AppServiceModel>
}
}
}
}
I have implemented ActionBar tabs following this guide: github. However I have a problem with the tab indicator getting stuck between the 2nd and 3rd tab. Like there is 4 tabs, but only 3 shown. Looks like this:
It's only when I slide from the 3rd tab to the 2nd. It just stays there, and if i slide left again, it goes to the 2nd tab. So it basically just feels like there is 4 tabs.
My FragmentPagerAdapter Class looks like this
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
private static Context context;
private String tabTitles[];
public SampleFragmentPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
Resources resources = context.getResources();
tabTitles = new String[] { resources.getString(R.string.recent),
resources.getString(R.string.popular),
resources.getString(R.string.my) };
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new RecentFragment();
case 1:
return new PopularFragment();
case 2:
return new MyFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public static class RecentFragment extends Fragment implements OnItemClickListener {
ListView listView;
List<RowItem> rowItems;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.custom_list, container, false);
String[] titles = { "titleA", "titleB", "titleC" };
String[] descriptions = { "a", "b", "c" };
Integer[] images = { R.drawable.christoffer, R.drawable.frede, R.drawable.sofie };
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
rowItems.add(item);
}
listView = (ListView) rootView.findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(context,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
return rootView;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
}
public static class PopularFragment extends Fragment {
}
public static class MyFragment extends Fragment {
}
}
My SlidingTabLayout and SlidingTabStrip classes looks excatly like the one in the guide. And in the MainActivity I have added this code to implement the tabs:
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(
getSupportFragmentManager(), MainActivity.this));
// Give the SlidingTabLayout the ViewPager
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
// Center the tabs in the layout
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setViewPager(viewPager);
// Customize tab color
slidingTabLayout
.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return Color.RED;
}
});
Please load fragment XML into all tabs through java file and it will solve..
I have a navigation drawer in which there is a ViewPager that extends a Fragment. When i click the item of drawer i open the viewpager in which there are three fragments. It works perfectly. but if i click again the same drawer item to open the viewpager another one time, the viewpager is empty.. I can see the tabs but not the fragments in there. This is the Viewpager:
public class ViewPagerManager extends Fragment {
public static ViewPagerManager instance = null;
Toolbar toolbar;
public static PagerSlidingTabStrip tabs;
public MyPagerAdapter adapter;
public ViewPager pager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_tabbed, container, false);
instance = this;
adapter = new MyPagerAdapter(getFragmentManager());
pager = (ViewPager)view.findViewById(R.id.pager);
tabs = (PagerSlidingTabStrip)view.findViewById(R.id.tabs);
pager.setAdapter(adapter);
tabs.setViewPager(pager);
pager.setOffscreenPageLimit(3);
adapter.notifyDataSetChanged();
pager.invalidate();
return view;
}
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "One", "Two", "Three" };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// Top Rated fragment activity
return new FragmentOne();
case 1:
// Games fragment activity
return new FragmentTwo();
case 2:
// Games fragment activity
return new FragmentThree();
}
return null;
}
}
}
Is it normal? How can i solve? If could help i'm using PagerSlidingTabStrip library.
Use this code
adapter = new MyPagerAdapter(getChildFragmentManager());
instead of
adapter = new MyPagerAdapter(getFragmentManager());
Try to redraw the last selected page when you return to the fragment. I think the viewpager is not cached and you need to reselect the last item. You can override the onresume method.
I am a beginner to android applications,I working around tab+swipe application,
my main class is like belove. please help me out.
public class MainScreenViewActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
private static String list_display_data1 = "item#sec1";
private static String list_display_data2 = "item#sec2";
private static String list_display_data3 = "item#sec3";
private static View rootView;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen_view);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
/*mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// When swiping between pages, select the
// corresponding tab.
getActionBar().setSelectedNavigationItem(position);
}
});*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_screen_view, menu);
return true;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = null;
fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(
R.layout.fragment_main_screen_view_dummy, container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
dummyTextView.setVisibility(View.INVISIBLE);
if(dummyTextView.getVisibility() == View.VISIBLE){
ListView sessionList = (ListView) rootView.findViewById(R.id.session_list);
initListView(getActivity(), sessionList, list_display_data1, 30, android.R.layout.simple_list_item_1);
}
else{
Log.d("", "");
}
//ListView sessionList = (ListView) rootView.findViewById(R.id.session_list);
//initListView(getActivity(), sessionList, list_display_data1, 30, android.R.layout.simple_list_item_1);
return rootView;
}
}
public static void initListView(Context context, ListView listView,String prefix, int numItems, int layout ){
// By using setAdpater method in listview we an add string array in list.
String[] arr = new String[numItems];
for(int i = 0; i< arr.length; i++){
arr[i] = prefix + (i +1);
}
listView.setAdapter(new ArrayAdapter<String>(context, layout, arr));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Context context = view.getContext();
String msg = "item[" + position + "]= " + parent.getItemIdAtPosition(position);
Toast.makeText(context, msg, 1000).show();
System.out.println(msg);
}
});
}
}
in onCreateView of dummySectionFragment how to add different list view. I just able to work on visibility of view.
You should Add Fragments to your viewpager for different page for different Tabs.