Trying to update my tab content - android

i´m using tablayout and i want to update the tab content when user clicks on the tab. basicly i want to do what the tab does when it is created (check what it is in database and put it on my listview).
here is my MainActivity:
public class MainActivity extends AppCompatActivity{
// Declaring Your View and Variables
Toolbar toolbar;
ViewPager viewPager;
ViewPagerAdapter adapter;
TabLayout tabLayout;
CharSequence Titles[]={"Participantes","Torneio","Classificação"};
int Numboftabs =3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
// Creating The Toolbar and setting it as the Toolbar for the activity
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
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.colorTextIcons));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
adapter.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
viewPager = null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_info) {
Toast.makeText(getApplicationContext(), "Contacto: Juniortalisson16#gmail.com", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is my ViewPageradapter:
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;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
FragmentManager manager = ((Fragment) object).getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove((Fragment) object);
trans.commit();
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
switch(position) {// if the position is 0 we are returning the First tab
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
case 2:
Tab3 tab3 = new Tab3();
return tab3;
default:
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;
}
}
i tried to use the getItemPosition but it didn´t work, my app crash when i select an tab.
Any ideias? please

Related

How to make my slow ViewPager to work faster

I've created Activity to handle ViewPager. At the beginning it was working fine, but then I had to add some more code, to make it refresh my pages while selecting them. I've handled it by calling onResume() method with every page change.
I've optimized my Fragments, cleared unnecessary code (inside onResume()) in each of them, but this give no result. That's how my Activity looks like:
public class MainTabsActivity extends AppCompatActivity implements FullList.OnListFragmentInteractionListener, AcceptedList.OnListFragmentInteractionListener, StartedList.OnFragmentInteractionListener {
private static final int NUM_TABS = 3;
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_tabs);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(2);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
Fragment fragment = ((SectionsPagerAdapter)mViewPager.getAdapter()).getFragment(i);
if (fragment != null) {
Log.e("PAGE SELECTED", " " + i);
tabLayout.getTabAt(i).select();
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
Intent i = getIntent();
int pageNum = i.getIntExtra("pagenumber", 0);
mViewPager.setCurrentItem(pageNum);
tabLayout.getTabAt(pageNum).select();
mViewPager.invalidate();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_tabs, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onListFragmentInteraction(DummyContent.DummyItem item) {
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
mFragmentTags = new HashMap<>();
mFragmentManager = fm;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch(position) {
case 0:
return getString(R.string.tab_text_1);
case 1:
return getString(R.string.tab_text_2);
case 2:
return getString(R.string.tab_text_3);
}
return null;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FullList tab1 = new FullList();
return tab1;
case 1:
AcceptedList tab2 = new AcceptedList();
return tab2;
case 2:
StartedList tab3 = new StartedList();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return NUM_TABS;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
Object obj = super.instantiateItem(container, position);
if (obj instanceof Fragment) {
Fragment f = (Fragment) obj;
String tag = f.getTag();
mFragmentTags.put(position, tag);
}
return obj;
}
public Fragment getFragment(int position) {
String tag = mFragmentTags.get(position);
if (tag == null) return null;
return mFragmentManager.findFragmentByTag(tag);
}
}
}
I've added code, to call onResume() method, but funny thing is that the Fragments are loading so long only while I open this Activity from another, but not while scrolling between pages (everything works smoothly then), before changes everything was fine.
Is there any way to make this work faster?
You don't need to write onPageSelected code to change your tab selection.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(2);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager); // this will synchronize our tablayout with your viewpager
You should not call onResume directly, this is a system event and a call to this void
is not recommended.
Also, in your case, no need to call mViewPager.invalidate()

During run time add or remove tabs in Tablayout with Fragmentpageradapter?

I have implemented TablLayout with FragmentPagerAdapter, I would like to add or remove Tabs but I am unsure how to implement this. I have searched for this but couldn't find it all other examples are similar but not the same as I am not using an arraylist and quite get my head around the tutorials.
This is the FragmentPagerAdapter
public class TabPagerAdapter extends FragmentPagerAdapter {
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount = numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1Fragment tab1 = new Tab1Fragment();
return tab1;
case 1:
Tab2Fragment tab2 = new Tab2Fragment();
return tab2;
case 2:
Tab3Fragment tab3 = new Tab3Fragment();
return tab3;
case 3:
Tab4Fragment tab4 = new Tab4Fragment();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
This is the activity
public class TabLayoutDemoActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_layout_demo);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1 Item").setIcon(android.R.drawable.ic_dialog_email));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2 Item").setIcon(android.R.drawable.ic_btn_speak_now));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3 Item").setIcon(android.R.drawable.ic_lock_idle_low_battery));
tabLayout.addTab(tabLayout.newTab().setText("Tab 4 Item").setIcon(android.R.drawable.ic_dialog_alert));
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new TabPagerAdapter(getSupportFragmentManager(), tabLayout
.getTabCount());
viewPager.setAdapter(adapter);
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) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_tab_layout_demo, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am using the support TabLayout and Viewpager , from what I know addition and removal of tab is to be done from the adapter class, so i tried to use this code but I can't figure out what is tablItems here referring to and how to set up this variable or is there any other way to do this ?
public void removeTabPage(int position) {
if (!tabItems.isEmpty() && position<tabItems.size()) {
tabItems.remove(position);
notifyDataSetChanged();
}
}

FragmentPagerAdapter GetItem is never called?

I'm trying to initate a simple tab swipe, But when I'm adding the PagerAdapter the getItem method is never called..
I cant find the reason for this.
Activity:
public class ProfileActivity extends Activity implements ActionBar.TabListener
{
ViewPager viewPager;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_acivity);
viewPager = (ViewPager) findViewById(R.id.profile_view_pager);
ProfilePagerAdapter viewPagerAdapter = new ProfilePagerAdapter(getFragmentManager());
viewPager.setAdapter(viewPagerAdapter);
viewPager.setCurrentItem(0);
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab friendsTab = actionBar.newTab();
ActionBar.Tab postsTab = actionBar.newTab();
ActionBar.Tab tribesTab = actionBar.newTab();
tribesTab.setText("TRIBES");
postsTab.setText("POSTS");
friendsTab.setText("FRIENDS");
tribesTab.setTabListener(this);
postsTab.setTabListener(this);
friendsTab.setTabListener(this);
actionBar.addTab(friendsTab);
actionBar.addTab(postsTab);
actionBar.addTab(tribesTab);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_profile_acivity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
}
(I also tried with FragmentActivity Though I do not need the V4 and I'm using the V13)
My adapter:
private class ProfilePagerAdapter extends FragmentPagerAdapter
{
Fragment fragment = new ProfileTribeFragment();
public ProfilePagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int i)
{
Log.i("D","NO :{");
if(i==0)
{
fragment = new ProfileFriendsFragment();
}
if(i==1)
{
fragment = new ProfilePostsFragment();
}
if(i==2)
{
fragment = new ProfileTribeFragment();
}
return fragment;
}
#Override
public int getCount()
{
return 0;
}
}
And all the 3 Fragments look like that:
public class ProfileTribeFragment extends Fragment {
public ProfileTribeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_profile_tribe, container, false);
}
}
I Just cant figure what I'm doing wrong.
The Log.i on the getItem is never seen.
you return Zero on your getCount() so there will be no Item inside your PagerAdapter:
#Override
public int getCount()
{
return 0;
}
Page adapter will bind no page as defined page count inside getCount() but in your case you have return static '0' zero count so pager adapter will not bind any page over there and you not able to seen any page data there. You need to set no page count inside getCount() method like 3 as below example :
#Override
public int getCount(){
return 3; // 3 is no of page count
}
For me nothing worked Then I found the solution - Instead of FragmentPagerAdapter, use FragmentStatePagerAdapter.
Return the number of fragments in getCount() method:
int fragmentCount=3;
#Override
public int getCount()
{
return fragmentCount;
}

How to add swipe in tabs

I am using support library to create action bar in my app. I have added actions in action bar thats working perfect. Now I edit tabs below that. But for changing tabs I have to click on tabs. I want to add swipe in this code. But Its difficult for me as I am taking reference from one link thats only show to add tabs and change them with on click on them. So please someone help me to add swipe from screen to change tabs.
Code-
public class Types extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.types);
setupTabs();
}
private void setupTabs() {
android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setNavigationMode( ActionBar.NAVIGATION_MODE_TABS );
Tab tab = ab.newTab()
.setText( R.string.frag1).setTabListener(new MyTabListener(this, Type1.class.getName()));
ab.addTab(tab);
tab = ab.newTab()
.setText( R.string.frag2).setTabListener(new MyTabListener( this, Type2.class.getName() ) );
ab.addTab(tab);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
homeActivity();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void homeActivity() {
Toast.makeText(this, "Home Option Selexted", Toast.LENGTH_SHORT).show();
}
private class MyTabListener implements ActionBar.TabListener
{
private Fragment mFragment;
private final Activity mActivity;
private final String mFragName;
public MyTabListener( Activity activity, String fragName )
{
mActivity = activity;
mFragName = fragName;
}
#Override
public void onTabReselected( Tab tab,
FragmentTransaction ft )
{
}
#Override
public void onTabSelected( Tab tab,
FragmentTransaction ft )
{
mFragment = Fragment.instantiate( mActivity, mFragName );
ft.add( android.R.id.content, mFragment );
}
#Override
public void onTabUnselected( Tab tab, FragmentTransaction ft )
{
ft.remove( mFragment );
mFragment = null;
}
}
Create ViewPagerAdapter class-
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final int PAGES = 4;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Type1();
case 1:
return new Type2();
case 2:
return new Type3();
case 3:
return new Type4();
default:
throw new IllegalArgumentException("The item position should be less or equal to:" + PAGES);
}
}
#Override
public int getCount() {
return PAGES;
}
}
Then in your Typle class-
public class Types extends ActionBarActivity {
private ViewPager viewPager;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.pagerad);
viewPager = (ViewPager) findViewById(R.id.pager);
ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setDisplayShowHomeEnabled(true);
viewPager.setOnPageChangeListener(onPageChangeListener);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
addActionBarTabs();
}
private ViewPager.SimpleOnPageChangeListener onPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
ab.setSelectedNavigationItem(position);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
homeActivity();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void homeActivity() {
Toast.makeText(this, "Home Option Selexted", Toast.LENGTH_SHORT).show();
}
private void addActionBarTabs() {
ab = getSupportActionBar();
String[] tabs = { "TYPE 1", "TYPE 2", "TYPE 3", "TYPE 4" };
for (String tabTitle : tabs) {
ActionBar.Tab tab = ab.newTab().setText(tabTitle).setTabListener(tabListener);
ab.addTab(tab);
}
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
private ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
}
Finally create pagerad xml-
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
Then create Each Type fragment like-
public class Type1 extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.type, container, false)
return rootView;
}
}
You need to use the ViewPager.
When implementing the viewpager from the android tutorial you simply need to focus on the getitem method of the SectionsPagerAdapter. Here you could pick the right fragment based on the position of the position of the "view".
Your challenge is that the swipe part of the app is now one activity only, and each view now must be implemented as a fragment. But this layout seems compatible with your current code (eg similar to the onTabSelected method).
You types.xml file should be a ViewPager:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.Types" />
Next, declare a ViewPager and SectionsPagerAdapter in you Types activity:
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
Now, in you OnCreate add:
// Create the adapter that will return a fragment for each swipe screen
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
The SectionsPagerAdapter is implemented as:
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.
if (position == 2) {
return new FragmentA();
} else if (position == 1) {
return new FragmentB();
} else {
// Pattern from you code...
return Fragment.instantiate( mActivity, mFragName );
}
}
#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;
}
}
That's all :)

Action bar tabs with viewpager with different page layouts

Hi Im new in android and I want ask for help. Im creating new project in android studio and I use navigation Action bar tabs with viewpager. Android studio generate this code. I know work with one activity atc but now I want to learn work with swipe layouts with tabs. My question is: Is possible do more layouts with different items inside this? For example, now I have on every fragment one textview and when I swipe I see any text on every page. But I need for example on page(tab1) layout with textview, on tab2 I need layout edittext, on tab3 I need layout with image. Is this possible with this? Because I can change text but now I have the same layout for all tabs.
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#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());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
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;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "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);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
In this case you can define 3 separate fragment classes. Then you can return them appropriately in getItem of your SectionsPagerAdapter:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new YourFragmentClass1();
case 1:
return new YourFragmentClass2();
case 2:
return new YourFragmentClass3();
}
}
To elaborate on Szymon's answer.
Step 1 Delete the inner class PlaceHolderFragment
Step 2: Create your fragment classes, with corresponding layouts. For example, ImageViewFragment (which extends Fragment of course) and then image_view_fragment_layout.
Step 3 Have ImageViewFragment's onCreateView method inflateimage_view_fragment_layout.
public ImageViewFragment extends Fragment {
...
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.image_view_fragment_layout,
container, false);
return rootView;
}
Follow these steps for as many tabs you want to add.
Then in the getItem() method follow Szymon's answer. Remember, the tab you want to appear first will be in position 0 and so on.
One more Important thing, in your getCount method:
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
the number returned should reflect the number of tabs you have added.

Categories

Resources