I try the code below to call another activity while pressing the back button:
#Override
public boolean onKeyUp(int keyCode, KeyEvent msg) {
switch(keyCode) {
case(KeyEvent.KEYCODE_BACK):
Intent intent = new Intent(AActivity.this, BActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window w = NASGroup.group.getLocalActivityManager().startActivity("BActivity", intent);
View view = w.getDecorView();
MyGroup.group.setContentView(view);
return true;
}
return false;
}
But when I press the back button, it get out of the app.
I see the logcat, it does not run the function onKeyUp and doesn't output any message.
The same code in onKeyUp, I try to below code to a button in layout and it works.
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AActivity.this, BActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window w = NASGroup.group.getLocalActivityManager().startActivity("BActivity", intent);
View view = w.getDecorView();
MyGroup.group.setContentView(view);
}
});
How can I modify it?
To handle back press you have to override Onbackpress method.
#Override
public void onBackPressed() {
finish();
Intent intent = new Intent(Myactivity.this, other.class);
startActivity(intent);
}
Try overriding the activity's onBackPressed() method
from the docs : onBackPressed
Try like this...
#Override
public void onBackPressed() {
Intent BackpressedIntent = new Intent();
BackpressedIntent .setClass(getApplicationContext(),TargetActivity.class);
BackpressedIntent .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(BackpressedIntent );
finish();
}
For back button you have to override the OnBackPressed() in your activity as
#Override
public void onBackPressed() {
Intent intent=new Intent(currentclass.this,nextActivity.class);
startActivity(intent);
finish();
}
if you didnt finish the previous activity then no need to use intent and startActivity just call finish(); in the onBackPressed it will finish the current activity and previous activity will started.
If you are within Activity you can use onBackPressed which is a built-in method to handle back key press.
Related
I've been trying to find out the back navigation button to lead to another activity.
Every time when I pressed the back button, it goes to the previous activity which is not what I want. I would like to set the back button that goes to another activity I want, instead of previous one.
For example, I have Activity 1, 2 and 3. I was in Activity 2 and just moved to Activity 3. But when I press the back button, it goes automatically to the previous activity which is Activity 2. I want to make it to Activity 1 and not Activity 2. Can anyone suggest me a solution please?
You can make the button to go to a specific activity, instead of having the default behavior that you described.
It can be something like this:
#Override
public void onClick(View v) {
Intent intent = new Intent(Activity2.this, Activity3.class);
intent.putExtra("variable", information); //this is optional, but can be useful if you need to send a specific info to the next activity
startActivity(intent);
}
Activity 2 is parliamonar, and Activity 3 is federalparliamentary. I replaced parliamonar with Activity 1, but it still didn't solve the problem.
public class federalparliamentary extends AppCompatActivity {
Button federal;
private Object parliamonar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_federalparliamentary);
federal = findViewById(R.id.back160);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), parliamonar.class);
startActivity(reserve);
}
});
federal = findViewById(R.id.next164);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), sar.class);
startActivity(reserve);
}
});
}
public void onClick(View V) {
Intent back = new Intent((Context) parliamonar, federalparliamentary.class);
startActivity(back);
}
}
public class federalparliamentary extends AppCompatActivity {
Button federal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_federalparliamentary);
federal = findViewById(R.id.back160);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), parliamonar.class);
startActivity(reserve);
}
});
federal = findViewById(R.id.next164);
federal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reserve = new Intent(getApplicationContext(), sar.class);
startActivity(reserve);
}
});
}
public void Onclick(View v) {
Intent intent = new Intent(federalparliamentary.this, politicalsystem.class);
startActivity(intent);
}
}
Activity 1 is "politicalsystem".
I added with #Override method, but it says that I have to remove the method, so I added outside, then it says that I have to extract interface, so clicked on it, then it gave me a bunch of list. So I chose onClick(v:View ):void, but it still didn't solve the issue. I tried in another way without #Override, but nothing changed when I tested my app. I also tried inside onCreate method which did not modified the navigation as I desired.
When i push the back button on the phone it opens the pause activity as intended but it also goes to the previous activity(i can see this because pause activity style is Theme.AppCompat.Dialog. What i want is just open the pause activity but in the backround to be the current activity not the previous one.The code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer_2);
//...
}
//...
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(timer_2.this, timer_2_pause.class));
finish();
}
In case you wish to kill previous activity use this:
#Override
public void onBackPressed()
{
startActivity(new Intent(timer_2.this, timer_2_pause.class));
finish();
}
If you want to keep that activity in back stack use this:
#Override
public void onBackPressed()
{
startActivity(new Intent(timer_2.this, timer_2_pause.class));
}
Try this:
#Override
public void onBackPressed() {
Intent i=new Intent(timer_2.this,timer_2_pause.class);
startActivity(i);
finish();
super.onBackPressed();
}
Its because you are calling finish() to close the current activity.
Remove finish() and it wont close the current activity.
You should use onBackPress() like this :
#Override
public void onBackPressed()
{
// super.onBackPressed();
// finish();
startActivity(new Intent(timer_2.this, timer_2_pause.class));
}
Use this just...
#Override
public void onBackPressed()
{
//super.onBackPressed(); dont use this..
finish();
startActivity(new Intent(timer_2.this, timer_2_pause.class));
}
Is it possible to define the source of a click? I can access my MainActivity through either clicking on a RecyclerView or through a Notification action. Depending on which it is, I need to provide different info. Is there a way of saying: if click is from recyclerview then..., else if it is from notification action then...?
What I can think of so far is this, but the problem is I am not using buttons as such:
Button mClickButton1 = (Button)findViewById(R.id.clickButton1);
mClickButton1.setOnClickListener(this);
Button mClickButton2 = (Button)findViewById(R.id.clickButton2);
mClickButton2.setOnClickListener(this);
public void onClick(View v) {
switch (v.getId()) {
case R.id.clickButton1: {
// do something for button 1 click
break;
}
case R.id.clickButton2: {
// do something for button 2 click
break;
}
}
}
Thanks!
you have to define two different calling intents for the same activity and put info for each View Example :
mClickButton1.setOnClickListener(new onClickListener(){
public void onClick(View v) {
Intent view1_int = new Intent (this, MainActivity.class);
view1_int.putExtra("Calling Intent" ,"RecyclerView");
startaActivityForResult(view1_int);
}
});
mClickButton2.setOnClickListener(new onClickListener(){
public void onClick(View v) {
Intent view2_int = new Intent (this, MainActivity.class);
view1_int.putExtra("Calling Intent" ,"Notification action");
startaActivityForResult(view1_int);
}
});
and in the onCreate Method in your MainActivity you can say :
String callin_view;
callin_view =getresources.getIntent.getExtras("Calling_Intent");
This will retrieve the name of the calling source you defined
So I've implemented a double press to exit on my mainactivity which exits fine if I go to settings activity or to game activity. However, if I go mainactivity --> gameactivity --> gameoveractivity and then press back it starts the mainactivity fine but then double pressing just returns to gameoveractivity and I'm not sure why as I call finish when starting mainactivity from gameoveractivity.
mainscreenactivity:
// button listeners
playButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent gameActivityIntent = new Intent(MainScreenActivity.this, GameActivity.class);
startActivity(gameActivityIntent);
overridePendingTransition(R.anim.righttocenter, R.anim.centertoleft);
finish();
}
});
settingsButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent settingsActivityIntent = new Intent(MainScreenActivity.this, SettingsActivity.class);
MainScreenActivity.this.startActivity(settingsActivityIntent);
overridePendingTransition(R.anim.righttocenter, R.anim.centertoleft);
}
});
gameactivity:
// handle hardware back button
#Override
public void onBackPressed() {
Intent mainScreenActivityIntent = new Intent(GameActivity.this, MainScreenActivity.class);
startActivity(mainScreenActivityIntent);
overridePendingTransition(R.anim.lefttocenter, R.anim.centertoright);
finish();
}
logic code to handle going to gameoveractivity:
if (weight.getBounds().intersect(player.getBounds())) {
timer.cancel();
gameTimer.cancel();
player.setTouched(false);
save(score, time);
Intent gameOverIntent = new Intent(this.getContext(), GameOverActivity.class);
this.getContext().startActivity(gameOverIntent);
((Activity) this.getContext()).finish();
}
gameoveractivity:
// handle hardware back button
#Override
public void onBackPressed() {
Intent mainScreenActivityIntent = new Intent(GameOverActivity.this, MainScreenActivity.class);
mainScreenActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
GameOverActivity.this.startActivity(mainScreenActivityIntent);
overridePendingTransition(R.anim.lefttocenter, R.anim.centertoright);
finish();
}
Edit: Managed to fix this by adding this: gameOverIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
in the game logic code after creating the gameoveractivityintent.
Managed to fix this by adding this:
gameOverIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
in the game logic code after creating the gameoveractivityintent.
I have a TabActivity that has a TabHost with two tabs. Each tab has its own intent. It seems like the intent's onResume() fires before I can detect if a tab was changed. How can I resolve this?
TabActivity code:
public class TabHostActivity extends TabActivity {
static final int SHOW_SHARE_ACTIVITY = 0;
static final int SHOW_LOGIN_ACTIVITY = 1;
private TabHost tabHost;
private ImageButton composeImageButton;
private SharedPreferences prefs;
private Bundle b;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tabhostactivity);
prefs = getSharedPreferences(Constants.PREFS_NAME, 0);
//Setup the ActionBar
composeImageButton = (ImageButton) findViewById(R.id.composeImageButton);
composeImageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(prefs.getBoolean("isLoggedIn", false))
{
showShareActivity();
}
else
{
Intent intent = new Intent(TabHostActivity.this, LoginActivity.class);
startActivityForResult(intent, SHOW_LOGIN_ACTIVITY);
}
}
});
b = new Bundle();
//Setup the Tabs
Resources res = getResources(); // Resource object to get Drawables
tabHost = getTabHost(); // The activity TabHost
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String arg0) {
if(tabHost.getCurrentTab() == 0) //Check if the Watchlist tab was clicked so we can prompt login
{
//Toast toast = Toast.makeText(getApplicationContext(), "TRENDING = YES", Toast.LENGTH_SHORT);
//toast.show();
b.putBoolean("isTrendingTab",true);
}
else
{
Toast toast = Toast.makeText(getApplicationContext(), "TRENDING = NO", Toast.LENGTH_SHORT);
toast.show();
b.putBoolean("isTrendingTab",false);
}
}
});
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, ARActivity.class);
intent.putExtras(b);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("trending").setIndicator("Trending",res.getDrawable(R.drawable.icon)).setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, WatchlistActivity.class);
intent.putExtras(b);
spec = tabHost.newTabSpec("watchlist").setIndicator("Watchlist",res.getDrawable(R.drawable.icon)).setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
}
private void showShareActivity()
{
Intent intent = new Intent(TabHostActivity.this, ShareActivity.class);
startActivityForResult(intent, SHOW_SHARE_ACTIVITY);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == SHOW_LOGIN_ACTIVITY)
{
//Login was successful so lets show the compose box!
if (resultCode == RESULT_OK) {
showShareActivity();
}
}
}
}
Here is the onResume in the Intent for one of my Activities:
public void onResume()
{
super.onResume();
Bundle bundle = getIntent().getExtras();
if(bundle.getBoolean("isTrendingTab"))
{
Toast toast = Toast.makeText(getApplicationContext(), "TRENDING!", Toast.LENGTH_SHORT);
toast.show();
}
else
{
Toast toast = Toast.makeText(getApplicationContext(), "WATCHLIST!", Toast.LENGTH_SHORT);
toast.show();
}
}
If i understood correctly the problem is that you try to put
b.putBoolean("isTrendingTab",true);
(or false) on the intent you're going to launch by detecting change.
That's the wrong approach.
The change event will always occur after the activity is launched, you should do the logic different. You have to rethink it.
Have you looked at Activity life cycle? The resume is being called when the activity is being created too and the line bundle.getBoolean("isTrendingTab") does not have a default value in case it has not been set yet...
Can you set it first in the onCreate to a default value? I think that is your issue. The code is a little sloppy. You are trying to pass variables to each activity but they still both exists in the tab activity. Views would be a better method so they all see the same variables in the tab activity.
The oncreate of your class ARActivity.class will be called before your onresume method of your tab host.
So do whatever the processing you want in your ARActivity.
Also since your tabHost.setCurrentTab(0); your starting tab will always be ARActivity.
And if you want to activate code depending your tab change, figure out which tab you are on using using the main tabhost ontabchange and use the id and then send a request to a inner broadcast receiver.
if (tabHost.getCurrentTab() == 0) {
i.setAction(getString(R.string.br_refresh_home_tab));
sendBroadcast(i);
} else {
i.setAction(getString(R.string.br_refresh_sports_tab));
sendBroadcast(i);
}
In your ARActivity,
protected class RefreshList extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
getString(R.string.br_refresh_home_tab))) {
}
}
}
There's no need to use onTabChanged().
Here's how I do it in my app (with some of your values pasted in). I add the boolean flag to the intent, not an extra bundle:
Intent intent = new Intent(action) // see notes below about "action"
.setClass(this, ARActivity.class)
.putExtra("isTrendingTab", true);
TabHost.TabSpec spec = tabHost.newTabSpec("trending")
.setIndicator("trending", getResources().getDrawable(drawableId))
.setContent(intent);
tabHost.addTab(spec);
Then in onResume():
if (getIntent().getBooleanExtra("isTrendingTab", false)) {...
I found that when using the same class for multiple tabs, I had to differentiate them with a different action string in each Intent constructor, as above. Otherwise it wouldn't create a new activity when switching between tabs of the same class. You don't appear to be doing this (yet), so you can continue to leave it out. I thought I'd mention it, since passing isTrendingTab suggests you might be heading down this route.