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();
}
Related
I am trying to launch new activity from intent but it is only working in one case, even though both the activities extend AppCompatActivity. I don't know what the issue is.
the launcher activities are working fine
<manifest>
<activity
android:name=".activities.home_page.HomePageNavActivity"
android:label="#string/title_activity_home_page_nav"
android:theme="#style/AppTheme"
android:windowSoftInputMode="adjustResize" />
<activity
android:name=".activities.UserProfileActivity"
android:parentActivityName=".activities.home_page.HomePageNavActivity"
android:windowSoftInputMode="adjustResize" />
<activity android:name=".activities.ProductDescription"
android:parentActivityName=".activities.home_page.HomePageNavActivity"
android:windowSoftInputMode="adjustResize"/>
MainActivity (HomePageNavActivity)
public class HomePageNavActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page_nav);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
navigation.setSelectedItemId(R.id.navigation_discover);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.navigation_discover:
fragment = new DiscoverFragment();
if(!Constant.currentBottomFragmentSelected.equals("discover") ) {
Constant.currentBottomFragmentSelected = "discover";
loadFragment(fragment);
}
return true;
case R.id.navigation_inbox:
Intent intent=new Intent(HomePageNavActivity.this,ProductDescription.class); //this intent is not working
HomePageNavActivity.this.startActivity(intent);
return true;
case R.id.navigation_profile:
Intent intent1 = new Intent(HomePageNavActivity.this, UserProfileActivity.class); //this intent is working
startActivity(intent1);
return true;
}
return false;
}
};
Activity1 (ProductDescription) (Not working)
public class ProductDescription extends AppCompatActivity {
FloatingActionButton fabLove,fabShare,fabCart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_description);
}
}
Activity2 (UserProfileActivity) (working)
public class UserProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
utoolbar = (Toolbar) findViewById(R.id.toolbarProfile);
setSupportActionBar(utoolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
imgBtn = findViewById(R.id.imgBtnSettings);
imgBtnLogout = findViewById(R.id.imgBtnLogout);
//remaining code consists of onClickListeners for different buttons
}
}
You have to remove HomePageNavActivity.this.startActivity(intent):
case R.id.navigation_inbox:
Intent intent = new Intent(HomePageNavActivity.this,ProductDescription.class);
startActivity(intent);
return true;
hello great community I have an app in which I am using bottom navigation with 4 fragments. to move to the last fragment the user must be logged in so when a new user open the app and tap on item 4 a login activity open.
the problem is when I backpress from login activity it moves me to the home fragment 1 which is ok but the state of the bottom navigation item doesn't changes the fragment 4 remain highlighted. so how to manage it that when I return back from the login activity the home fragment item should be highlighted.
[
this is my BottomNAvigation main activity
public class Bottom_Nav extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
SparseArray<Fragment> myFragments;
String user_type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom__nav);
SharedPreferences sharedPreferences = getSharedPreferences("DataStore", Context.MODE_PRIVATE);
user_type = sharedPreferences.getString("user_type", "");
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
Nav_Helper.disableShiftMode(bottomNavigationView);
//make array to avoid re creating of fragments
myFragments = new SparseArray<Fragment>();
//loading the default fragment
loadFragment(new HomeFragment());
//getting bottom navigation view and attaching the listener
bottomNavigationView.setOnNavigationItemSelectedListener(this);
}
private void loadFragment(Fragment fragment) {
//switching fragment
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content, fragment);
fragmentTransaction.commit();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
int id = item.getItemId();
if (id == R.id.navigation_home) {
fragment = new HomeFragment();
myFragments.put(1, fragment);
loadFragment(fragment);
} else if (id == R.id.navigation_use) {
getFragmentManager().popBackStack();
switch (user_type) {
case "detailer":
fragment = new Detailer_Zone();
myFragments.put(4, fragment);
loadFragment(fragment);
break;
case "customer":
fragment = new Customer_Zone();
myFragments.put(4, fragment);
loadFragment(fragment);
break;
case "empty":
Intent intent = new Intent(this, Login_Activity.class);
startActivity(intent);
break;
}
}
else if (id == R.id.navigation_search) {
// get cached instance of the fragment
fragment = myFragments.get(2);
// if fragment doesn't exist in myFragments, create one and add to it
if (fragment == null) {
fragment = new SearchFragment();
myFragments.put(2, fragment);
}
loadFragment(fragment);
} else if (id == R.id.navigation_map) {
// get cached instance of the fragment
fragment = myFragments.get(3);
// if fragment doesn't exist in myFragments, create one and add to it
if (fragment == null) {
fragment = new MapsActivity();
myFragments.put(3, fragment);
}
loadFragment(fragment);
}
return true;
}
Case for Login:
case "empty":
Intent intent = new Intent(this, Login_Activity.class);
startActivityForResult(intent , 101);
break;
Login activity:
When user click on back button execute below code.
setResult(RESULT_CANCELED);
finish();
Handle case in Bottom_Nav activity :
// This method is called when the second activity finishes
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == 101) {
if (resultCode == RESULT_CANCELED) {
onNavigationItemSelected(menuItem)
}
}
}
Try this work around. Replace your case "empty": with this:
case "empty":
bottomNavigationView.setSelectedItemId(R.id.navigation_home);
Intent intent = new Intent(this, Login_Activity.class);
startActivity(intent);
break;
Tell me if this works.
I am new to Android Development And I am trying to create an application with bottomNavigationView. I have created a separate class to setup the bottomNavigationView for different activities so that I don't have to write the code again and Again. But when I launch the app in an Android device it is starting the Welcome activity again no matter what item I click it start Welcome activity. This is my navigationHelperClass
public class BottomNavigationViewHelper {
private static final String TAG = "BottomNavigationViewHel";
public static void setUpNavigationView(BottomNavigationViewEx bottomNavigationViewEx){
Log.d(TAG, "setUpNavigationView: setting BottomNavigation");
bottomNavigationViewEx.enableAnimation(false);
bottomNavigationViewEx.enableItemShiftingMode(false);
bottomNavigationViewEx.enableShiftingMode(false);
bottomNavigationViewEx.setTextVisibility(false);
}
public static void enableNavigation(final Context context, final BottomNavigationViewEx viewEx){
viewEx.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.btnHome:
viewEx.setSelectedItemId(R.id.btnHome);
Intent intent = new Intent(context, Welcome.class);
context.startActivity(intent);
break;
case R.id.btnSearch:
Intent intent1 = new Intent(context, Chats.class);
context.startActivity(intent1);
break;
case R.id.btnPost:
Intent intent2 = new Intent(context, Posts.class);
context.startActivity(intent2);
break;
case R.id.btnFavourites:
Intent intent3 = new Intent(context, Favourites.class);
context.startActivity(intent3);
break;
case R.id.btnProfile:
Intent intent4 = new Intent(context, Profile.class);
context.startActivity(intent4);
break;
}
return false;
}
});
}
}
This is my Welcome activity which starts when I click any of the item of bottomNavigationView.
public class Welcome extends AppCompatActivity {
private Context mCntext = Welcome.this;
private static final String TAG = "Welcome";
BottomNavigationViewEx bottomNav;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
Log.d(TAG, "onCreate: starting");
setupBottomNavigationView();
Menu menu = bottomNav.getMenu();
MenuItem menuItem = menu.getItem(0);
menuItem.setChecked(true);
private void setupBottomNavigationView(){
Log.d(TAG, "setupBottomNavigationView: setting bottomnavigationview");
bottomNav = findViewById(R.id.nav_bottom);
BottomNavigationViewHelper.setUpNavigationView(bottomNav);
BottomNavigationViewHelper.enableNavigation(mCntext, bottomNav);
}
}
This is one of the activities that I have and the code is same for the rest of activities too . This is Profile activitity.
public class Profile extends AppCompatActivity {
private Context mContext = Profile.this;
private static final String TAG = "Search";
BottomNavigationViewEx bottomNav;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
setupBottomNavigationView();
}
private void setupBottomNavigationView(){
Log.d(TAG, "setupBottomNavigationView: setting bottomnavigationview");
bottomNav = findViewById(R.id.nav_bottom);
BottomNavigationViewHelper.setUpNavigationView(bottomNav);
BottomNavigationViewHelper.enableNavigation(mContext, bottomNav);
Menu menu = bottomNav.getMenu();
MenuItem menuItem = menu.getItem(4);
menuItem.setChecked(true);
}
#Override
public void setTitle(CharSequence title) {
}
}
Remove following line:
viewEx.setSelectedItemId(R.id.btnHome);
from case case R.id.btnHome: under onNavigationItemSelected callback.
Do not use bottom navigation with activities instead use Fragments. Create a parent activity which will hold your fragments and then change the fragments in onNavigationItemSelectListener in that case you don't have to manage bottom navigation states and selected item. you can check here how to change fragments How to change fragment with the Bottom Navigation Activity?
I am A Beginner in android development, actually I have a Navigation drawer with Fragments my issue is when i go to fragment b from a the state in navigation drawer is updating to fragment b successfully but when go to fragment B From Fragment A by on 'backpressed' method the drawer item state is not updating / changing to fragment A . please help me in fixing this.
Here is my Main Activity Code :
public class MainActivity extends AbsRuntimePermission implements NavigationView.OnNavigationItemSelectedListener {
//, GoogleApiClient.OnConnectionFailedListener {
private static final int REQUEST_PERMISSION = 10;
private Toolbar toolBar;
private NavigationView navDrawer;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
private View btnLogOut;
private int selectedItem;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
// private GoogleApiClient googleApiClient;
private FloatingActionButton fab;
private CoordinatorLayout coordinatorLayout;
private HomeFragment homeFragment=new HomeFragment();
final String TAG = this.getClass().getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
auth = FirebaseAuth.getInstance();
final FirebaseUser user = auth.getCurrentUser();
String userID = user.getUid();
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Contact_FAB.class);
startActivity(intent);
}
});
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main_content, homeFragment);
tx.commit();
final WebView webView = (WebView) findViewById(R.id.WV);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
}
public void onPageFinished(WebView view, String url) {
// do your stuff here}
#Override
public void onReceivedError (WebView view,int errorCode, String description, String
failingUrl){
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
webView.loadUrl("https://google.co.in");
requestAppPermissions(new String[] {
Manifest.permission.READ_CONTACTS,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
R.string.msg,REQUEST_PERMISSION);
toolBar =(Toolbar)
findViewById(R.id.app_bar);
setSupportActionBar(toolBar);
// If a notification message is tapped, any data accompanying the notification
// message is available in the intent extras. In this project the launcher
// intent is fired when the notification is tapped, so any accompanying data would
// be handled here. If you want a different intent fired, set the click_action
// field of the notification message to the desired intent. The launcher intent
// is used when no click_action is specified.
//
// Handle possible data accompanying notification message.
if(
getIntent().
getExtras() !=null)
{
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
if (key.equals("AnotherActivity") && value.equals("True")) {
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("value", value);
startActivity(intent);
finish();
}
}
}
// subscribeToPushService();
drawerLayout =(DrawerLayout)
findViewById(R.id.drawer_layout);
navDrawer =(NavigationView)
findViewById(R.id.menu_drawer);
navDrawer.setNavigationItemSelectedListener(this);
drawerToggle =new
ActionBarDrawerToggle(this,drawerLayout, toolBar, R.string.drawer_open, R.string.drawer_close);
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
selectedItem =savedInstanceState ==null?R.id.nav_item_1 :savedInstanceState.getInt("selectedItem");
}
#Override
public boolean onNavigationItemSelected (MenuItem menuItem){
menuItem.setChecked(true);
selectedItem = menuItem.getItemId();
Fragment fragment = null;
switch (selectedItem) {
case R.id.nav_item_1:
fragment = new HomeFragment();
break;
case R.id.nav_item_2:
fragment = new MicrosoftDskFragment();
break;
case R.id.nav_item_3:
fragment = new GoogleDskFragment();
break;
case R.id.nav_item_4:
fragment = new AppleDskFragment();
break;
case R.id.nav_item_5:
fragment = new OthersDskFragment();
break;
case R.id.nav_item_6:
fragment = new MobiSpecsFragment();
break;
case R.id.nav_item_8:
Intent intent = new Intent(MainActivity.this, About.class);
startActivity(intent);
break;
default:
break;
}
if (!DetectConnection.checkInternetConnection(MainActivity.this)) {
Toast.makeText(MainActivity.this, "Plz check your network connectivity", Toast.LENGTH_SHORT).show();
} else {
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_content, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
boolean twice = false;
#Override
public void onBackPressed () {
DrawerLayout layout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (layout.isDrawerOpen(GravityCompat.START)) {
layout.closeDrawer(GravityCompat.START);
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
Log.d(TAG, "click");
if (twice == true) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
twice = true;
Log.d(TAG, "twice: " + twice);
//super.onBackPressed();
Toast.makeText(MainActivity.this, "Please Press Again To Exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice = false;
Log.d(TAG, "twice: " + twice);
}
}, 3000);
}
}
}
#Override
public boolean onKeyDown ( int keyCode, KeyEvent event){
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
homeFragment.OnKeyDown(keyCode);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#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_main, menu);
return super.onCreateOptionsMenu(menu);
}
#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.profile) {
Intent intent = new Intent(MainActivity.this, Profile.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState){
super.onSaveInstanceState(outState, outPersistentState);
outState.putInt("selectedItem", selectedItem);
}
#Override
public void onPermissionsGranted ( int requestCode){
//Do anything when permisson granted
// Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_LONG).show();
}
/* #Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
*/
}
}
When you popBackStack() the fragment from back stack will appear on screen so you need to listen for Back stack changes.
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.containerFrame);
if (fragment != null) {
// check for fragment and set the drawer state
if(fragment instanceof Frag1){
// set drawer state for 1
}else if(fragment instanceof Frag2){
// set drawer state for 2
}
}
}
});
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.