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;
Related
I have two activities,one is a MainActivity which has navigation drawer working.The Other is a testActivity which extends from the MainActivity.When I move from the MainActivity to the testActivity the navigation bar appears there but not working when i click there.
I have read too many posts on this like extending navigation drawer activity to other activities but I didnt understand them.
The following is my MainActivity
public class MainActivity extends AppCompatActivity {
private DrawerLayout dl;
private ActionBarDrawerToggle t;
private NavigationView nv;
Button nextBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dl = (DrawerLayout) findViewById(R.id.activity_main);
t = new ActionBarDrawerToggle(this, dl, R.string.Open, R.string.Close);
nextBtn = (Button)findViewById(R.id.nextAct);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,TestActivity.class);
startActivity(intent);
}
});
dl.addDrawerListener(t);
t.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nv = (NavigationView) findViewById(R.id.nv);
nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.account:
Toast.makeText(MainActivity.this, "My Account", Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Toast.makeText(MainActivity.this, "Settings", Toast.LENGTH_SHORT).show();
break;
case R.id.mycart:
Toast.makeText(MainActivity.this, "My Cart", Toast.LENGTH_SHORT).show();
break;
default:
return true;
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(t.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
}
The following is the testActivity.
public class TestActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
}
The second activity gets the navigation bar as i have extended this from the MainActivity but that is not clickable in this new activity.Can any edit the code so that it will be clickable.
I think that the best way to do this is to use fragments. The navigation drawer + bar stays the same, and you change fragments in the rest of the screen. Hope it helps !
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();
}
When I click on the back button, my MainActivity reopens. Why is this happening?
I integrated navigation-drawer in my MainActivity, and after this, when I click on the back button, the MainActivity is recreated. If I click again on the back button, the application gets closed.
This is my MainActivity code:
public class BuildingsActivity extends AppCompatActivity implements BuildingsNavigator,
BuildingItemNavigator, NavigationView.OnNavigationItemSelectedListener {
private ActivityBuildingsBinding binding;
private BuildingsViewModel viewModel;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_buildings);
viewModel = new BuildingsViewModel(this);
viewModel.loadBuildings();
viewModel.dataLoading.set(true);
if (!AppUtils.isOnline()) {
startForResult();
}
binding.setViewModel(viewModel);
binding.recycler.setLayoutManager(new GridLayoutManager(getApplicationContext(), 2));
binding.recycler.setAdapter(new BuildingAdapter(new ArrayList<Building>(0), this, this));
drawerLayout = binding.drawer;
toolbar = binding.actionToolbar;
setSupportActionBar(toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
navigationView = binding.buildingNavigation;
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.building_nav_item:
break;
case R.id.delivery_nav_item:
Intent deliveryIntent = new Intent(this, new DeliveryActivity().getClass());
startActivity(deliveryIntent);
item.setChecked(false);
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
Any suggestions?
Try to add to manifest: android:noHistory="true"
<activity android:name=".MainActivity"
android:screenOrientation = "portrait"
android:noHistory="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
or you can write handler for this button
#Override
public void onBackPressed() {
//add what you need, for example if you want to start another activity:
Intent intent = new Intent(AnotherActivity.this, MainActivity.class);
//or if you want to close:
this.finish();
//or
finish();
}
or if you about button on ActionBar you can write it in menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_item:
//something
return true;
case android.R.id.home:
//what you need
return true;
}
return super.onOptionsItemSelected(item);
}
the Previous Activity you are coming from Has a code that it sending it back to the current activity you are in, in its onstart() method. try finishing the previous activity before entering the current one
#Override
protected void onStart() {
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (mFirebaseUser != null) {
Intent mIntent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(mIntent);
}
super.onStart();
}
Try finishing the Activity after the Authentication
#Override
protected void onStart() {
FirebaseUser mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (mFirebaseUser != null) {
Intent mIntent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(mIntent);
finish();
}
super.onStart();
}
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?
For some reason this activity has the back arrow in the actionbar, but when it is clicked it has no reaction, doesn't even seen to recognize the click. I have other activities that are similar that work fine though. Here is the code with some stuff removed:
public class LanguageActivity extends ActionBarActivity {
private static final String TAG = "LanguageActivity";
#InjectView(R.id.listView)
RecyclerView mRecyclerView;
#State
String selectedLang;
LangViewHolder selectedHolder = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Icepick.restoreInstanceState(this, savedInstanceState);
setContentView(R.layout.recyclerview);
ButterKnife.inject(this);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.ad_title_settings_lang);
selectedLang = PreferencesFacade.getInstance().getCurrentLang();
mRecyclerView.setLayoutManager(new TrueWrapContentLinearLayoutManager(this));
List<Pair<String, String>> langList = new LinkedList<>();
langList.add(Constants.Languages.US);
langList.add(Constants.Languages.LATIN_AMERICA_SPANISH);
mRecyclerView.setAdapter(new RecycleViewMappedArrayAdapter(R.layout.view_language_item, new LangViewHolder(mRecyclerView), langList));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Icepick.saveInstanceState(this, outState);
super.onSaveInstanceState(outState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void finish() {
super.finish();
PreferencesFacade.getInstance().setCurrentLang(selectedLang);
Log.v(TAG, "Finishing?");
}
public class LangViewHolder extends RecycleViewMappedArrayAdapter.ViewHolder<Pair<String, String>>{
...
}
}
Manifest snippet:
<activity android:name=".activities.LanguageActivity"
android:parentActivityName=".activities.MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activities.MainActivity"/>
</activity>
This seems to be working for me:
Toolbar tBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(tBar); // sets the Toolbar as the actionbar
tBar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp));
tBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed(); // calls the System onBackPressed method
}
});
Update:
getDrawable(int id) is depreciated so you should change this line of code:
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= Build.VERSION_CODES.LOLLIPOP){
tBar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp, getApplicationContext().getTheme()));
} else {
tBar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp));
}
why don't You extend AppCompatActivity(i think actionbaractivity is deprecated...)
?
and
Toolbar toolbar = (Toolbar) findViewById(R.id.the_id);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//try this instead
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});