How to change Tab according to Intent in android? - android

I have a Activity named as Wallet and have a Activity named as CRechargeMain which adds two frgament named as "Mobile","Data";what I want in Wallet screen I have a Listview in which in case 0: when I click I want to go to CRechargeMain and show"Mobile" tab and in case 1 : when I click I want to go CRechareMain and open tab " data" .how can I do that
code for wallet:-
m_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent mMobileRecharges = new Intent(CMyWalletScreen.this,CRechargeMain.class);
startActivity(mMobileRecharges);
break;
case 1:
Intent mDataRecharge = new Intent(CMyWalletScreen.this,CRechargeMain.class);
startActivity(mDataRecharge);
break;
case 2:
Intent m_Earning= new Intent(CMyWalletScreen.this,CWalletTransactionScreen.class);
startActivity(m_Earning);
break;
}
}
});
code for CRechargeMain:-
public class CRechargeMain extends AppCompatActivity {
View m_Main;
private ViewPager m_ViewPager;
private Toolbar m_ToolBar;
private String[]actonBar={"Mobile Recharge","Mobile Data Recharge"};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recharge_main);
init();
}
public void init() {
m_ToolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(m_ToolBar);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
m_ToolBar.setTitle("Mobile Recharge");
TabLayout m_TabLayout = (TabLayout) findViewById(R.id.tab_layout);// finding Id of tablayout
m_TabLayout.addTab(m_TabLayout.newTab().setText("Mobile"));// add deal listin tab
m_TabLayout.addTab(m_TabLayout.newTab().setText("Data Card"));// add stories tab
m_TabLayout.setTabGravity(TabLayout.GRAVITY_FILL);// setting Gravity of Tab
m_ViewPager = (ViewPager) findViewById(R.id.pager);//finding Id of ViewPager
CRechargePager m_oMobilePager = new CRechargePager
(getSupportFragmentManager(), m_TabLayout.getTabCount());
m_ViewPager.setAdapter(m_oMobilePager);// adiing adapter to ViewPager
m_ViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(m_TabLayout));// performing action of page changing
m_TabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
m_ViewPager.setCurrentItem(tab.getPosition());
m_ToolBar.setTitle(actonBar[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_wallet, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}

You can use the same intent and select tab based on the intent argument in your activity.

As my assumption you are having two activity, activity1 contains list and activity2 contains fragments.from activity1 based on conditions you have to jump to activity2 (fragments).Just call as below
Intent i =New Intent(this,CRechargeMain.class);
i.putExtra("",0);
startActivity(i);
In Activty2 on create method based on conditions you have to set fragment to load.
FragmentManager FM = getFragmentManager();
FM.beginTransaction().replace(R.id.content_frame, detail).commit();

Intent mMobileRecharges = new Intent(CMyWalletScreen.this,CRechargeMain.class);
intent.putExtra("doWhat", 0);
Intent mDataRecharge = new Intent(CMyWalletScreen.this,CRechargeMain.class);
intent.putExtra("doWhat", 1);
In your receiving activity:
int iDoWhat = intent.getIntExtra("doWhat", -1);
Then make your decision based on the value of iDoWhat.
int iDoWhat = getIntent().getIntExtra("doWhat",-1);
switch (iDoWhat) {
case -1:
//select tab 0
break;
case 0:
//select tab 0
break;
case 1:
//select tab 1
break;
}
You have to write the code for selecting the tab now you know which one.

Related

BottomNavigationView from another Activity

I have MainActivity which contains fragments (for example 3 fragments) and I can select fragment by BottomNavigationView.
Also i have button in OneFragment which start SecondActivity (which also contains BottomNagigationView).
My question: When in SecondActivity i select bottomNV itemId two, I need to back to MainActivity with selected TwoFragment.
How can i realize it?
MainActivity.class
public class MainActivity extends AppCompatActivity {
private BottomNavigationView navigationView;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
navigationView = findViewById(R.id.navigationBottom);
navigationView.setOnNavigationItemSelectedListener(navListelener);
getSupportFragmentManager().beginTransaction().replace(R.id.content_main,
new OneFragment()).commit();
}
public BottomNavigationView.OnNavigationItemSelectedListener navListelener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
setTitle(item.getTitle());
switch (item.getItemId()){
case R.id.bottom_one:
selectFragment(new OneFragment());
break;
case R.id.bottom_two:
selectFragment(new TwoFragment());
break;
case R.id.bottom_three:
selectFragment(new ThreeFragment());
break;
}
return true;
}
};
private void selectFragment(Fragment selectedFragment){
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_main, selectedFragment)
.commit();
}
}
SecondActivity.class
public class SecondActivity extends AppCompatActivity {
private BottomNavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seconda);
navigationView = findViewById(R.id.navigationBottom);
navigationView.setOnNavigationItemSelectedListener(navListener);
Menu menu = navigationView.getMenu();
MenuItem menuItem = menu.getItem(1);
menuItem.setChecked(true);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.bottom_one:
finish();
break;
case R.id.bottom_two:
//need to return to MainActivity with selected TwoFragment
break;
case R.id.bottom_three:
break;
}
return true;
}
};
}
I have seen in your code that the second activity is called SecondaActivity instead of SecondActivity. I supposed it is being misspelled and my code reflects the last one.
You can start the second activity using (someRequestCode is just a random int you can choose):
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, someRequestCode);
Then in your second activity you can return OK in case 2 and KO in other cases (just for simplicity. If you want to elaborate a bit more you response, you can add some extra):
case R.id.bottom_two:
//need to return to MainActivity which selected TwoFragment
Intent data = new Intent();
data.putExtra("key", "value"); // You can add data if needed. For example, number of fragment to be changed
setResult(RESULT_OK, data);
finish();
break;
And finally in your MainActivity, override onActivityResult (someRequestCode is the same value as stated before):
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == someRequestCode) {
if (resultCode == RESULT_OK) {
// Here you can get key, value pair from extra and act accordingly
selectFragment(new TwoFragment());
} else {
// Do something else
}
}
}
case R.id.bottom_two:
//need to return to MainActivity which selected TwoFragment
Intent intent = new Intent(SecondaActivity.this,MainActivity.class);
intent.puExtra("fragment_no",2);
startActivity(intent);
finish();
break;
In MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
navigationView = findViewById(R.id.navigationBottom);
navigationView.setOnNavigationItemSelectedListener(navListelener);
Bundle extras = getIntent().getExtras();
if(extras!=null)
{ intent number = extras.getInt("fragment_no");
if(number == 2)
getSupportFragmentManager().beginTransaction().replace(R.id.content_main,
new TwoFragment()).commit();
}
else
getSupportFragmentManager().beginTransaction().replace(R.id.content_main,
new OneFragment()).commit();
}

Start a tab fragments from an activity with the tabs layout

I have a tab fragments app. The problem is when I go into an activity inside my app and want going back to my tabs layout it returns without the tabs row layout. I can see only the specific fragment page without the row above (the tab's row) that makes me able to navigate between the tabs.
Do you know what can I do to solve it? How can I see the tab's row too?
Thanks for any help,
This is the first tab that I want to see back from the activity:
public class Tab1MyProfile extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1_my_profile, container, false);
return rootView;
}
}
This is the activity that contains code to go back to the fragment tab:
public class GameLive extends AppCompatActivity implements RecognitionListener {
private Intent intent;
private Button mStopButton;
public void stopGame (View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to finish the game?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Tab1MyProfile fragment = new Tab1MyProfile();
fragmentTransaction.replace(android.R.id.content, fragment);
fragmentTransaction.commit();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_live);
mStopButton = (Button) findViewById(R.id.btnEndGame);
mStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopGame(view);
}
});
}
}
And this is the activity that contains all the tab's fragment:
public class StartActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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_start, 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);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1MyProfile tab1=new Tab1MyProfile();
return tab1;
case 1:
Tab2StartGame tab2=new Tab2StartGame();
return tab2;
case 2:
Tab3StatsArea tab3=new Tab3StatsArea();
return tab3;
case 3:
Tab4Settings tab4=new Tab4Settings();
return tab4;
}
return null;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "My profile";
case 1:
return "Start Game";
case 2:
return "Stats Area";
case 3:
return "Settings";
}
return null;
}
}
}
Thank again!
What if you replace everything inside the onClick method of the DialogInterface.OnClickListener with GameLive.this.finish();. This will close the GameLive activity on click and return you to the previous activity, which should be the one that contains the missing navigation bar.

How to open speific tab from passing Intent in android?

I have a activity call "Wallet" in which there in implementation of switch case in and having another activity that contain tablayout in which 1st tab named as "Mobile" and 2nd tab named as "Data".what I want from activity "Wallet" switch case in case0: i am passing Intent to another activity that contain tablayout want to open tab "Mobile" and on case 1: Intent want to open tab "Data".How can I do that please tell me.
code for Wallet switch:-
m_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent mMobileRecharges = new Intent(CMyWalletScreen.this,CRechargeMain.class);
startActivity(mMobileRecharges);
break;
case 1:
Intent mDataRecharge = new Intent(CMyWalletScreen.this,CRechargeMain.class);
startActivity(mDataRecharge);
break;
case 2:
Intent m_Earning= new Intent(CMyWalletScreen.this,CWalletTransactionScreen.class);
startActivity(m_Earning);
break;
}
}
});
and code for TablayOut Activity :-
public class CRechargeMain extends AppCompatActivity {
View m_Main;
private ViewPager m_ViewPager;
private Toolbar m_ToolBar;
private String[]actonBar={"Mobile Recharge","Mobile Data Recharge"};
int iDoWhat;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recharge_main);
Intent intent = new Intent();
init();
}
public void init() {
m_ToolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(m_ToolBar);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
m_ToolBar.setTitle("Mobile Recharge");
TabLayout m_TabLayout = (TabLayout) findViewById(R.id.tab_layout);// finding Id of tablayout
m_TabLayout.addTab(m_TabLayout.newTab().setText("Mobile"));// add deal listin tab
m_TabLayout.addTab(m_TabLayout.newTab().setText("Data Card"));// add stories tab
m_TabLayout.setTabGravity(TabLayout.GRAVITY_FILL);// setting Gravity of Tab
m_ViewPager = (ViewPager) findViewById(R.id.pager);//finding Id of ViewPager
CRechargePager m_oMobilePager = new CRechargePager
(getSupportFragmentManager(), m_TabLayout.getTabCount());
m_ViewPager.setAdapter(m_oMobilePager);// adiing adapter to ViewPager
m_ViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(m_TabLayout));// performing action of page changing
m_TabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
m_ViewPager.setCurrentItem(tab.getPosition());
m_ToolBar.setTitle(actonBar[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_wallet, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Check following your example
m_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent mMobileRecharges = new Intent(CMyWalletScreen.this,CRechargeMain.class);
mMobileRecharges.putExtra("tab_position",0);
startActivity(mMobileRecharges);
break;
case 1:
Intent mDataRecharge = new Intent(CMyWalletScreen.this,CRechargeMain.class);
mDataRecharge.putExtra("tab_position",1);
startActivity(mDataRecharge);
break;
case 2:
Intent m_Earning= new Intent(CMyWalletScreen.this,CWalletTransactionScreen.class);
startActivity(m_Earning);
break;
}
}
});
// CRechargeMain Activity
Add one line in your code
m_TabLayout.getTabAt(getIntent().getIntExtra("tab_position", 0)).select()
public class CRechargeMain extends AppCompatActivity {
View m_Main;
private ViewPager m_ViewPager;
private Toolbar m_ToolBar;
private String[]actonBar={"Mobile Recharge","Mobile Data Recharge"};
int iDoWhat;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recharge_main);
Intent intent = new Intent();
init();
}
public void init() {
m_ToolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(m_ToolBar);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
m_ToolBar.setTitle("Mobile Recharge");
TabLayout m_TabLayout = (TabLayout) findViewById(R.id.tab_layout);// finding Id of tablayout
m_TabLayout.addTab(m_TabLayout.newTab().setText("Mobile"));// add deal listin tab
m_TabLayout.addTab(m_TabLayout.newTab().setText("Data Card"));// add stories tab
m_TabLayout.setTabGravity(TabLayout.GRAVITY_FILL);// setting Gravity of Tab
m_ViewPager = (ViewPager) findViewById(R.id.pager);//finding Id of ViewPager
CRechargePager m_oMobilePager = new CRechargePager
(getSupportFragmentManager(), m_TabLayout.getTabCount());
m_ViewPager.setAdapter(m_oMobilePager);// adiing adapter to ViewPager
m_ViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(m_TabLayout));// performing action of page changing
m_TabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
m_ViewPager.setCurrentItem(tab.getPosition());
m_ToolBar.setTitle(actonBar[tab.getPosition()]);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
// Add this line in your code
m_TabLayout.getTabAt(getIntent().getIntExtra("tab_position", 0)).select();
}
#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_wallet, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
In Wallet Activity pass 0/1 from intent.
In CRechargeMain Just add following code.
//here tab index 0 or 1
m_TabLayout.getTabAt(0).select();

ActionBarActivity back button to fragment

I have problem with the back button in action bar to fragment
my code fragment:
public class Server extends Fragment {
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_server, container, false);
Button server = (Button) view.findViewById(R.id.status);
/** Button Check Status Server **/
server.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(view.getContext(), ServerStatus.class);
startActivityForResult(myIntent, 0);
getActivity().finish();
}
});
return view;
}
}
my code in activity:
public class ServerStatus extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_status);
}
}
My code in Fragment
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new Account();
break;
case 1:
objFragment = new AllNews();
break;
case 2:
objFragment = new Server();
break;
case 3:
objFragment = new Account();
break;
case 4:
objFragment = new Account();
break;
case 5:
objFragment = new Account();
break;
case 6:
objFragment = new About();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container,objFragment)
.commit();
}
Every time I click the back button, the program always closes. I already tried to use:
getActionBar().setDisplayHomeAsUpEnabled(true);
and this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
Can anyone help me to fix my program?
EDIT: Concerning cross-activity-navigation, you should not use startActivityForResult() in that way. Try to use startActivity() instead. If you start an activity for a result, the calling activity waits for the onActivityResult() callback and should not be finished.
In the manifest file you should declare the fragment's activity as parent activity of ServerStatus to enable back navigation. You should not need NavUtils.
If you want to enable fragment navigation within an activity, you have to add your fragment transactions to the backstack:
getFragmentManager().beginTransaction().addToBackStack(null).replace(...).commit();
Then you have to call getFragmentManager().popBackStack() in onOptionsItemSelected() to enable back navigation for the action bar:
#override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
getFragmentManager().popBackStack();
return true;
}
return super.onOptionsItemSelected(item);
}
You may have to override onBackPressed() to enable back navigation for the back button:
#override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() >= 1) {
getFragmentManager().popBackStack(); // return to previous fragment
}
else {
super.onBackPressed(); // Exit application when no fragment is on the backstack
}
}

FragmentPagerAdapter getItem() is returning more than it should

I have a MainActivity that controls four fragments, each of which is a tab. When my main activity starts, I have a line being printed to the log to show me what fragment is being instantiated. Here is my FragmentPagerAdapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
System.out.println("Returning new PrearrivalPlan()");
return new PrearrivalPlan();
case 1:
System.out.println("Returning new PrimarySurvey()");
return new PrimarySurvey();
case 2:
System.out.println("Returning new SecondarySurvey()");
return new SecondarySurvey();
case 3:
System.out.println("Returning new PrepareForTravel()");
return new PrepareForTravel();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
The tab bar has the following options in order:
Prearrival Plan | Primary Survey | Secondary Survey | Prepare for Travel
When my main activity starts, the following is printed to the screen:
Returning new PrearrivalPlan()
Returning new PrimarySurvey()
What it seems to be doing is loading one tab ahead of the one I have selected. Since PrearrivalPlan is the first tab, I would think it should just return a new PrearrivalPlan() except it returns both. Another example, when I click on Primary Survey tab (second tab), the following is printed to the screen:
Returning new SecondarySurvey() // <- This is the third tab!?
Because PrimarySurvey was already instantiated when the activity first started (see output above), it jumped ahead just like it did before and loaded the third tab even though I only clicked on the second.
Here is my MainActivity:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
private CustomViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabTitles = {"Pre-arrival Plan", "Primary Survey", "Secondary Survey", "Prepare for Travel"};
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (CustomViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
viewPager.setPagingEnabled(false);
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager.setOnPageChangeListener(new CustomViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
// Remove Android icon from Action Bar
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
getActionBar().setDisplayShowHomeEnabled(false);
// Add tabs to Action Bar
for (String tab_name : tabTitles) {
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void updateTabTitles(int tabNumber, int checkBoxesRemaining) {
String text = tabTitles[tabNumber] + " \n (" + checkBoxesRemaining + ")";
actionBar.getTabAt(tabNumber).setText(text);
}
#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) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
return true;
case R.id.complete:
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
goToReport();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to complete the checklist?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToReport() {
Intent intent = new Intent(this, Report.class);
startActivity(intent);
}
It is the expected behaviour of ViewPager. ViewPager always keeps one tab ahead and behind in memory in order to show slider animation. If you don't you have the next or previous tab (or fragment) in memory, trying to initiate the fragment during the slider transition will cause a performance lag or at the worse you will have the sliding fragment to be empty and get loaded later.
ViewPager also allows you to set page offset limit through setOffscreenPageLimit() which will control amount fragment to keep them in memory. By default, this is 1 which means one fragment ahead and behind will always be there in memory

Categories

Resources