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>
}
}
}
}
Related
I have a viewPager activity that makes multiple fragments with custom FragmentPagerAdapter.
I need to get the List<Audio> audioList and use it in my fragment.
Here is a small part of my MainActivity where I make the fragments. I do not think the rest of the MainActivity code is required in order to answer this question.
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
PagerAdapter pagerAdapter =
new PagerAdapter(getSupportFragmentManager(), MainActivity.this, audioList);
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
Here is my custom FragmentPagerAdapter:
public class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] { "Recommended", "Popular", "Rock", "Pop", "Blues", "Chill" };
Context context;
private List<Audio> audioList;
public PagerAdapter(FragmentManager fm, Context context, List<Audio> audioList) {
super(fm);
this.context = context;
this.audioList = audioList;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new BlankFragment();
case 1:
return new BlankFragment();
case 2:
return new BlankFragment();
case 3:
return new BlankFragment();
case 4:
return new BlankFragment();
case 5:
return new BlankFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
And I need to get the List<Audio> audioList into my Fragment here:
public class BlankFragment extends Fragment {
public BlankFragment() {
// 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.content_view, container, false);
//Get auidoList here
return rootView;
}
I also need to get the title of the tab in the future but my guess is that I would get it similarly to the audioList. If it is not then I could also use help on getting the tab title.
Additionally if the code style is wrong then I am always happy to have some feedback on it aswell.
The traditional way of doing this is by having an instance method that moves it all via a bundle.
Like this:
public class BlankFragment extends Fragment {
public static BlankFragment newInstance(String title, ArrayList<Audio> audioList) {
BlankFragment blankFragment = new BlankFragment();
Bundle bundle = new Bundle();
bundle.putString("Title", title);
bundle.putParcelableArrayList("AudioList", audioList);
blankFragment.setArguments(bundle);
return blankFragment;
}
public BlankFragment() {
// Required empty public constructor
}
private String title;
private ArrayList<Audio> audioList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
title = bundle.getString("Title");
audioList = getArguments().getParcelableArrayList("AudioList");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.content_view, container, false);
//Get auidoList here
return rootView;
}
}
Obviously your Audio class will need to implement parcelable for this to work. I found a great plugin (Android Parcelable Code Generator) in Android Studio for generating parcelable code that makes that quick and easy.
I have an Activity with 2 fragments.
Declared a ParentTabFragment in my Activity in which there is a TabLayout and a ViewPager.
There's a method in my ParentTabFragment called addPage which gets called in the Activity.
The addPage has another method called addFrag which is called from a ViewPagerAdapter creating the views in the ChildTabFragment dynamically.
There is a for loop which runs in the Activity, so the Fragments are created according to the number of items in the customList, creating the amount of tabs and pages in the Fragments.
In my ChildTabFragment I load a customList on tab selection event,
when I select a Tab in the ParentTabFragment, I call a getTabID() method from the ChildTabFragment and send the id of the Tab due to which I load the customList according to the id in the ParentTabFragment.
Problem is when I swipe or select tabs, duplicate/false data gets created in the customList.
I get the proper Id of the selected tab but when I try to pass it in the method, random id is called.
In my Activity Class:
for (int j =0;j<it.size();j++){
parentTabFragment.addPage(it.get(j).getTabMenuItem(), it.get(j).getTabMenuId() , selectedMenu);
}
ParentTabFragment:
public void addPage(String pagename, String pageId, String selectedMenu) {
Bundle bundle = new Bundle();
bundle.putString("data", pagename);
//bundle.putString("pageID", pageId);
childTabFragment = new ChildTabFragment();
childTabFragment.setArguments(bundle);
adapter.addFrag(childTabFragment, pagename, pageId);
adapter.notifyDataSetChanged();
if (selectedMenu == null) {
viewPager.setCurrentItem(0);
} else {
for (int i = 0; i < tabLayout.getTabCount(); i++) {
if (tabLayout.getTabAt(i).getText().equals(selectedMenu)) {
viewPager.setCurrentItem(i);
}
}
}
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
ChildTabFragment:
public class ChildTabFragment extends Fragment {
String childname;
int menuItemId;
TextView textViewChildName, txtViewItemId;
ListView childTabMenuList;
private ArrayList<ChildTabMenu_POJO> childTabMenuPojoList = new ArrayList<>();
private ListView listView;
private ChildTabMenuAdapter childTabMenuAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.child_tab_fragment, container, false);
Bundle bundle = getArguments();
childname = bundle.getString("data");
getIDs(view);
return view;
}
private void getIDs(View view) {
childTabMenuList = (ListView) view.findViewById(R.id.childTabMenuList);
loadChildMenu();
}
private void loadChildMenu(menuItemId) {
ChildTabMenu_POJO menu_pojo4 = new ChildTabMenu_POJO(String.valueOf(menuItemId), "4");
childTabMenuPojoList.add(menu_pojo4);
childTabMenuAdapter = new ChildTabMenuAdapter(childTabMenuPojoList, getActivity());
childTabMenuList.setAdapter(childTabMenuAdapter);
}
public void getTabID(int tabId) {
menuItemId = tabId;
Log.e("updatefrag", String.valueOf(menuItemId));
}
}
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<Adapter_POJO> mFragmentTitleList = new ArrayList<>();
Context context;
ViewPager viewPager;
TabLayout tabLayout;
Adapter_POJO adapter_pojo;
public ViewPagerAdapter(FragmentManager manager, Context context, ViewPager viewPager,
TabLayout tabLayout) {
super(manager);
this.context = context;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public int getItemCount() {
return mFragmentTitleList.size();
}
public void addFrag(Fragment fragment, String title, String pageId) {
mFragmentList.add(fragment);
adapter_pojo = new Adapter_POJO(title,pageId);
mFragmentTitleList.add(adapter_pojo);
}
public View getTabView(final int position) {
View view = LayoutInflater.from(context).inflate(R.layout.view_pager_adapter_layout, null);
TextView tabItemName = (TextView) view.findViewById(R.id.textViewTabItemName);
tabItemName.setText(mFragmentTitleList.get(position).adapterMenuItem);
tabItemName.setTextColor(context.getResources().getColor(android.R.color.background_light));
return view;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position).adapterMenuItem;
}
public String getPageId(int position){
return mFragmentTitleList.get(position).adapterMenuId;
}
}
If i understand your question so you need to create newInstance constructor for creating fragment with arguments
public static ChildTabFragment newInstance(int page, String title) {
FirstFragment fragmentFirst = new FirstFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
And Store instance variables based on arguments passed in your ChildTabFragment .
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
And now update the view in your onCreateView method
TextView tvLabel = (TextView) view.findViewById(R.id.tvLabel);
tvLabel.setText(page + " -- " + title);
And the main thing you should returns the ChildTabFragment to display for that page from your ViewPagerAdapter like this.
#Override
public Fragment getItem(int position) {
return ChildTabFragment.newInstance(position,"page "+String.valueOf(position));
}
So when the user swipes through each page, I want an intent to be launched at the end; to show the main activity. Right now I set the number of pages to be 4 so that when the user swipes to the 4th page, the user gets sent to my main activity. However my app crashes
Fragment activity
public class ScreenSlideActivity extends FragmentActivity {
private static final int NUM_PAGES = 4;
ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
public void onBackPressed() {
int pos = mPager.getCurrentItem();
if (pos == 0) {
super.onBackPressed();
} else mPager.setCurrentItem(pos - 1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new adapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
private class adapter extends FragmentStatePagerAdapter {
public adapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 4) {
Intent intent = new Intent(getApplication(), MainActivity.class);
startActivity(intent);
}
return ScreenSlidePageFragment.initialize(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
fragment
public class ScreenSlidePageFragment extends Fragment {
int position;
String[] text = {"Be more productive", "Choose your own work and rest times", "Login to access full features"};
int[] images = {R.drawable.productivity, R.drawable.workingguy, R.drawable.logincmon};
public static ScreenSlidePageFragment initialize(int position) {
ScreenSlidePageFragment page = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt("POSITION", position);
page.setArguments(args);
return page;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt("POSITION", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
TextView tv = (TextView) v.findViewById(R.id.MainText);
ImageView image = (ImageView) v.findViewById(R.id.MainImage);
tv.setText(text[position]);
image.setImageResource(images[position]);
return v;
}
}
Change the validation to start the Intent to 3, not 4.
Remember that lists start counting the indexes in 0.
#Override
public Fragment getItem(int position) {
if (position == 3) { // position 3 is the page #4
Intent intent = new Intent(getApplication(), MainActivity.class);
startActivity(intent);
finish();
}
return ScreenSlidePageFragment.initialize(position);
}
The error that you receive is that you are calling ScreenSlidePageFragment.initialize(3). In ScreenSlidePageFragment the String[] text and int[] images contains 3 elements (from index 0..2).
This will cause ArrayIndexOutOfBoundsException at runtime and crash the app.
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 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.