Title of the last tab in my ViewPager doesn't show - java

Title of the last tab in my ViewPager doesn't show, in this case i have 4 tabs but only the first 3 tabs are shown but not the last one although I can swipe to the fourth tab
Code
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import java.util.Objects;
import it.neokree.materialtabs.MaterialTab;
import it.neokree.materialtabs.MaterialTabHost;
import it.neokree.materialtabs.MaterialTabListener;
public class MainActivity extends AppCompatActivity implements
MaterialTabListener {
MaterialTabHost tabHost;
ViewPager viewPager;
ViewPagerAdapter androidAdapter;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = this.findViewById(R.id.toolBar);
tabHost = this.findViewById(R.id.tabHost);
viewPager = this.findViewById(R.id.viewPager);
androidAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(androidAdapter);
viewPager.setOnPageChangeListener(new
ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int tabposition) {
tabHost.setSelectedNavigationItem(tabposition);
}
});
for (int i = 1; i < androidAdapter.getCount(); i++) {
tabHost.addTab(
tabHost.newTab()
.setText(Objects.requireNonNull(androidAdapter.getPageTitle(i)))
.setTabListener(this)
);
}
}
#Override
public void onTabSelected(MaterialTab materialTab) {
viewPager.setCurrentItem(materialTab.getPosition());
}
//tab on reselected
#Override
public void onTabReselected(MaterialTab materialTab) {
}
//tab on unselected
#Override
public void onTabUnselected(MaterialTab materialTab) {
}
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
public Fragment getItem(int num) {
return new AndroidFragment();
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int tabposition) {
return "Tab " + tabposition;
}
}}
Title of the last tab in my ViewPager doesn't show, in this case i have 4 tabs but only the first 3 tabs are shown but not the last one although I can swipe to the fourth tab

Change this line:
for (int i = 1; i < androidAdapter.getCount(); i++)
to
for (int i = 0; i < androidAdapter.getCount(); i++)
You are missing 1 tab

Related

Update Tab fragment TextViews during runtime

I have been researching how to accomplish an activity with tabs and have gotten very close to completion. Unfortunately, I have hit a bit of a roadblock.
After following a great guide, I created an interactive activity with a tabLayout and a ViewPager to display the fragment.
Each tab displays the same layout, which is a column of TextViews on the left which keep their default value, and another column of TextViews that need to get their value from different locations.
As a test, I had each tab send different text values to their respective TextViews (example Tab #1 was assigned to use "Downstairs", #2 was assigned to use "Upstairs") - which is accomplished through the onTabSelected listener.
The issue I am running in to, is when the text is assigned to the TextViews. It never displays when the tab is selected. It sometimes displays on the next tab I open. It also sometimes displays Tab 1 assignment values in Tab 3 after I had already opened tab 2 before opening tab 3.
Every other TextView I have worked with updates right away when I use setText(). However, I am very new to using Tab Activities, so I very well could be messing something up.
Distribution.java
package local.mobileapps.bryandouglas.supremeshoppinglist;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class Distribution extends FragmentActivity {
private Context context;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_distribution);
context = this;
viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
TabFragment.cream.setText("Downstairs");
TabFragment.freshnessBottles.setText("Downstairs");
TabFragment.soap.setText("Downstairs");
TabFragment.paperCups.setText("Downstairs");
TabFragment.shortStirSticks.setText("Downstairs");
TabFragment.longStirSticks.setText("Downstairs");
TabFragment.cafeRoyale.setText("Downstairs");
TabFragment.hotChocolate.setText("Downstairs");
TabFragment.equal.setText("Downstairs");
TabFragment.sugar.setText("Downstairs");
TabFragment.greenTea.setText("Downstairs");
TabFragment.orangePekoe.setText("Downstairs");
break;
case 1:
TabFragment.cream.setText("Upstairs");
TabFragment.freshnessBottles.setText("Upstairs");
TabFragment.soap.setText("Upstairs");
TabFragment.paperCups.setText("Upstairs");
TabFragment.shortStirSticks.setText("Upstairs");
TabFragment.longStirSticks.setText("Upstairs");
TabFragment.cafeRoyale.setText("Upstairs");
TabFragment.hotChocolate.setText("Upstairs");
TabFragment.equal.setText("Upstairs");
TabFragment.sugar.setText("Upstairs");
TabFragment.greenTea.setText("Upstairs");
TabFragment.orangePekoe.setText("Upstairs");
break;
case 2:
TabFragment.cream.setText("Shipping");
TabFragment.freshnessBottles.setText("Shipping");
TabFragment.soap.setText("Shipping");
TabFragment.paperCups.setText("Shipping");
TabFragment.shortStirSticks.setText("Shipping");
TabFragment.longStirSticks.setText("Shipping");
TabFragment.cafeRoyale.setText("Shipping");
TabFragment.hotChocolate.setText("Shipping");
TabFragment.equal.setText("Shipping");
TabFragment.sugar.setText("Shipping");
TabFragment.greenTea.setText("Shipping");
TabFragment.orangePekoe.setText("Shipping");
break;
case 3:
TabFragment.cream.setText("Solutions");
TabFragment.freshnessBottles.setText("Solutions");
TabFragment.soap.setText("Solutions");
TabFragment.paperCups.setText("Solutions");
TabFragment.shortStirSticks.setText("Solutions");
TabFragment.longStirSticks.setText("Solutions");
TabFragment.cafeRoyale.setText("Solutions");
TabFragment.hotChocolate.setText("Solutions");
TabFragment.equal.setText("Solutions");
TabFragment.sugar.setText("Solutions");
TabFragment.greenTea.setText("Solutions");
TabFragment.orangePekoe.setText("Solutions");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
TabFragment.java
package local.mobileapps.bryandouglas.supremeshoppinglist;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import static android.content.Context.MODE_PRIVATE;
public class TabFragment extends Fragment {
protected static final String ADMIRAL_DOWNSTAIRS_PREFS_NAME = "AdmiralDownstairsPrefsFile";
protected static final String ADMIRAL_UPSTAIRS_PREFS_NAME = "AdmiralUpstairsPrefsFile";
protected static final String ADMIRAL_SHIPPING_PREFS_NAME = "AdmiralShippingPrefsFile";
protected static final String SOLUTIONS_PREFS_NAME = "SolutionsPrefsFile";
protected static SharedPreferences AdmiralDownstairsData;
protected static SharedPreferences AdmiralUpstairsData;
protected static SharedPreferences AdmiralShippingData;
protected static SharedPreferences SolutionsData;
protected static SharedPreferences.Editor editor;
int position;
protected static TextView cream;
protected static TextView freshnessBottles;
protected static TextView soap;
protected static TextView paperCups;
protected static TextView shortStirSticks;
protected static TextView longStirSticks;
protected static TextView cafeRoyale;
protected static TextView hotChocolate;
protected static TextView equal;
protected static TextView sugar;
protected static TextView greenTea;
protected static TextView orangePekoe;
public static Fragment getInstance(int position) {
Bundle bundle = new Bundle();
bundle.putInt("pos", position);
TabFragment tabFragment = new TabFragment();
tabFragment.setArguments(bundle);
return tabFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt("pos");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tab, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
cream = view.findViewById(R.id.lblCreamValue);
freshnessBottles = view.findViewById(R.id.lblMilkValue);
soap = view.findViewById(R.id.lblSoapValue);
paperCups = view.findViewById(R.id.lblCupValue);
shortStirSticks = view.findViewById(R.id.lbl4_5StirValue);
longStirSticks = view.findViewById(R.id.lbl7StirValue);
cafeRoyale = view.findViewById(R.id.lblCafeRoyaleValue);
hotChocolate = view.findViewById(R.id.lblHotChocValue);
equal = view.findViewById(R.id.lblEqualValue);
sugar = view.findViewById(R.id.lblSugarValue);
greenTea = view.findViewById(R.id.lblGreenTeaValue);
orangePekoe = view.findViewById(R.id.lblOrangePekoeValue);
}
}
ViewPagerAdapter.java
package local.mobileapps.bryandouglas.supremeshoppinglist;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
class ViewPagerAdapter extends FragmentPagerAdapter {
private String title[] = {"Admiral - Downstairs", "Admiral - Upstairs", "Admiral - Shipping", "Solutions"};
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return TabFragment.getInstance(position);
}
#Override
public int getCount() {
return title.length;
}
#Override
public CharSequence getPageTitle(int position) {
return title[position];
}
}
I was attempting to design it in a way that uses SharedPreferences to store and read persistent data. There is a specific sharedPrefs files for each corresponding tab. You will notice that sharedPrefs have not been implemented, and is that way as I wanted to test with just basic setText.

TabLayout with Tab selected counter

What I would like to accomplish is:
When ever the user clicks on Tab 1, it should increment a counter and display it on the fragment. I originally thought about, using tabLayout.setOnTabSelectedListener how ever this did not work as it gave me the following error; "setOnTabSelectedListener is deprecated. I also tried doing getId however that did not work either as I was unable to register when the user clicked the tab.
Please help!
When ever the user clicks Tanav Sharma it should increment a counter that is displayed.
package tanav.sharma;
import android.support.v4.app.Fragment;
import android.content.DialogInterface;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
import tanav.sharma.R;
import tanav.sharma.OneFragment;
import tanav.sharma.TwoFragment;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class TanavActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_action_pro,
R.drawable.ic_action_web
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tanav);
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/**
* This button is responsible for taking the user back
* to the main activity. Preventing the user from pressing
* the back key multiple times.
*/
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager)findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout)findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupTabIcons(){
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
}
private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), getApplicationContext().getString(R.string.tanav));
adapter.addFragment(new TwoFragment(), "TWO");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
/**
* This function is responsible for prompting the user with a dialog box,
* once the hit the back key on the app. Asking for confirmation if they,
* really want to exit the app. If user selects Yes, the app will quit.
* If the user selects cancel, the app will continue to run.
*/
#Override
public void onBackPressed() {
CharSequence exit = getApplicationContext().getString(R.string.exit);
CharSequence exit_message = getApplicationContext().getString(R.string.exit_message);
new AlertDialog.Builder(this)
.setTitle(exit)
.setMessage(exit_message)
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
TanavActivity.super.onBackPressed();
}
}).create().show();
}
}
Below code works to keep count :)
package tanav.sharma;
import android.support.v4.app.Fragment;
import android.content.DialogInterface;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
import tanav.sharma.R;
import tanav.sharma.OneFragment;
import tanav.sharma.TwoFragment;
import android.util.Log;
import android.view.View;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class TanavActivity extends AppCompatActivity {
private RatingBar ratingBar;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_action_pro,
R.drawable.ic_action_web
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tanav);
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/**
* This button is responsible for taking the user back
* to the main activity. Preventing the user from pressing
* the back key multiple times.
*/
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager)findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout)findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
int count_image = 0;
int count_web = 0;
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
if(position == 0){
count_image = count_image + 1;
TextView counter = (TextView) findViewById(R.id.counter);
counter.setText(Integer.toString(count_image));
}else if(position == 1){
//count_web = count_web + 1;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
count_image = count_image + 1;
TextView counter = (TextView) findViewById(R.id.counter);
counter.setText(Integer.toString(count_image));
}
});
}
private void setupTabIcons(){
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
}
private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), getApplicationContext().getString(R.string.tanav));
adapter.addFragment(new TwoFragment(), "TWO");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
/**
* This function is responsible for prompting the user with a dialog box,
* once the hit the back key on the app. Asking for confirmation if they,
* really want to exit the app. If user selects Yes, the app will quit.
* If the user selects cancel, the app will continue to run.
*/
#Override
public void onBackPressed() {
CharSequence exit = getApplicationContext().getString(R.string.exit);
CharSequence exit_message = getApplicationContext().getString(R.string.exit_message);
new AlertDialog.Builder(this)
.setTitle(exit)
.setMessage(exit_message)
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
TanavActivity.super.onBackPressed();
}
}).create().show();
}
}

how to add tab layout in activity with theme.holo.light.darkactionbar

i am adding menu icon by making custom Actionbar and extends my class with Activity. This is working properly but when i add Tablayout in the xml file android studio throws an exception for using appcompat theme. After using Appcompat theme in my project custom actionbar menu icons it gives an exception of java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
This is my code:
package com.dzirecreatives.showvoo;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.dzirecreatives.showvoo.Fragments.CreateEventsFrag;
import com.dzirecreatives.showvoo.Fragments.TicketsFrag;
import com.dzirecreatives.showvoo.Fragments.TrendingFrag;
import com.dzirecreatives.showvoo.adapter.TitleNavigationAdapter;
public class TrendingTicketsEvents extends Activity implements ActionBar.OnNavigationListener {
ImageView search_action;
// action bar
private ActionBar actionBar;
private TitleNavigationAdapter titleNavigationAdapter;
TabLayout tab_trending_tickets_events;
ViewPager viewPager_trending_tickets_events;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trending_tickets_events);
actionBar = getActionBar();
//actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
titleNavigationAdapter = new TitleNavigationAdapter(getApplicationContext());
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#454545")));
actionBar.setListNavigationCallbacks(titleNavigationAdapter, this);
// viewPager_trending_tickets_events= (ViewPager) findViewById(R.id.viewPager_trending_tickets_events);
// //viewPager_trending_tickets_events.setAdapter(new CustomAdapter(this.getSupportFragmentManager(),getApplicationContext()));
// tab_trending_tickets_events= (TabLayout) findViewById(R.id.tab_trending_tickets_events);
// tab_trending_tickets_events.setupWithViewPager(viewPager_trending_tickets_events);
// tab_trending_tickets_events.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
// #Override
// public void onTabSelected(TabLayout.Tab tab) {
// viewPager_trending_tickets_events.setCurrentItem(tab.getPosition());
// }
//
// #Override
// public void onTabUnselected(TabLayout.Tab tab) {
// viewPager_trending_tickets_events.setCurrentItem(tab.getPosition());
// }
//
// #Override
// public void onTabReselected(TabLayout.Tab tab) {
// viewPager_trending_tickets_events.setCurrentItem(tab.getPosition());
// }
// });
}
private class CustomAdapter extends FragmentPagerAdapter {
private String fragment[]={"Trending","Tickets","Create Events"};
public CustomAdapter(FragmentManager supportFragmentManager, Context applicationContext) {
super(supportFragmentManager);
}
#Override
public int getCount() {
return fragment.length;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new TrendingFrag();
case 1:
return new TicketsFrag();
case 2:
return new CreateEventsFrag();
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return fragment[position];
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_menu_action, menu);
RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.search_action).getActionView();
search_action = (ImageView) badgeLayout.findViewById(R.id.img_search);
search_action.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Choosecity();
}
});
return true;
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
return false;
}
}

Android fragment tabbed layout, reselecting tab 3, listview disappears

When I select tab 3 my listview appears, yet when I select tab 1 and reselect tab 3, the listview doesn't appear.
Why is this?
https://github.com/jdavey1996/News-Android-App
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Local"));
tabLayout.addTab(tabLayout.newTab().setText("Top rated"));
tabLayout.addTab(tabLayout.newTab().setText("All"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
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) {
}
});
}
}
package com.josh_davey.news_app;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class FragmentAdapter extends FragmentPagerAdapter {
int count;
public FragmentAdapter(FragmentManager fm, int count) {
super(fm);
this.count = count;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment1 temp = new Fragment1();
return temp;
case 1:
Fragment2 temp2 = new Fragment2();
return temp2;
case 2:
Fragment3 temp3 = new Fragment3();
return temp3;
}
return null;
}
#Override
public int getCount() {
return count;
}
}
package com.josh_davey.news_app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment3 extends Fragment {
public Fragment3() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GetData getData = new GetData(getContext(),getActivity());
getData.execute("lincoln");
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment3, container, false);
}
}
If you need link to the full code it's on my github. Thanks in advance for any help
https://github.com/jdavey1996/News-Android-App
Default ViewPager's offscreenPageLimit is 1. So the tab3 is detached when tab1 is re-selected. If fragment is detached, Fragment's views are destroyed.
see: ViewPager.setOffscreenPageLimit
So I recommend you to set offscreenPageLimit to 2.
viewPager.setOffscreenPageLimit(2);
Or you can hold the list of ArticleConstructor in Fragment3 like blew.
GetData.java:
public class GetData extends AsyncTask<String, String,ArrayList<ArticleConstructor>>{
Callback callback;
interface Callback {
void onArticleConstructorLoaded(ArrayList<ArticleConstructor> articleConstructors);
}
public GetData(Callback callback) {
this.callback = callback;
}
...
#Override
protected void onPostExecute(ArrayList<ArticleConstructor> result) {
callback.onArticleConstructorLoaded(result);
}
....
}
Fragment3.java:
public class Fragment3 extends Fragment implements GetData.Callback {
private ListView listView;
private ArrayList<ArticleConstructor> articleConstructors = new ArrayList<>();
private ArticleArrayAdapter adapter;
public Fragment3() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment3, container, false);
listView = (ListView) view.findViewById(R.id.listView);
adapter = new ArticleArrayAdapter(getActivity(), getContext(), articleConstructors);
listView.setAdapter(adapter);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (articleConstructors.size() == 0) {
GetData getData = new GetData(this);
getData.execute("lincoln");
}
}
#Override
public void onArticleConstructorLoaded(ArrayList<ArticleConstructor> articleConstructors) {
this.articleConstructors = articleConstructors;
adapter.setArticleConstructors(articleConstructors);
}
}

Android: Switching activities in swipeable tab layout

In my android app there is a swipeable tab layout. It has two tabs: New Complain and Previous Complains. When click the complain tab I need to start NewComplain.java. Here is my NewComplain class code segment:
NewComplain class
public class NewComplain extends SherlockFragmentActivity implements View.OnClickListener {
private int Year;
private int Month;
private int Day;
private static final int DATE_DIALOG_ID = 1;
private View viewLoad;
private TextView heading, date;
private Spinner spiComplain, spiProduct;
private EditText description, contInfo;
private Button btnDate;
private ArrayAdapter<String> complainAdapter, prodAdapter;
private ArrayList<String> lstComplain = new ArrayList<String>();
private ArrayList<String> lstProdNames = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
viewLoad = LayoutInflater.from(NewComplain.this).inflate(
R.layout.new_complain, null);
setContentView(viewLoad);
}
}
This id my TabsPagerAdapter class.
package xont.virtusel.v4.controller.sale;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
case 1:
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
}
And this is my main activity class.
package xont.virtusel.v4.controller.sale;
import xont.virtusel.v4.controller.R;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class CustomerComplainActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "New Complain", "Previous Complains" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setDisplayHomeAsUpEnabled(true);
//actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//actionBar.setDisplayShowHomeEnabled(false);
//actionBar.setDisplayShowTitleEnabled(false);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
How should I add switching activity statements into this TabsPagerAdapter class. I used intent. But it's not worked.
Can anyone plz be so kind enough to clarify this issue.
Thanx in advance
What exactly is your problem?
If you can't start new Fragment, try this:
in TabsPagerAdapter in public Fragment getItem() method
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new NewComplain();
case 1:
//return some other class
}
return null;
}
and create a constructor for NewComplain class
You are adding fragments, not activities. In your Tab listeners, you are given a FragmentTransaction which you should be using to update which of your fragments is showing with respect to the tab pressed.
Also, don't inflate in fragment on create, do that in on create view.

Categories

Resources