Android onBackPressed() is not being called? - java

in my MainActivity, which extends from AppCompatActivity, I want to override the onBackPressed method like so:
#Override
public void onBackPressed() {
Log.d("MainActivity","onBackPressed");
Toast.makeText(getApplicationContext(),"onBackPressed",Toast.LENGTH_SHORT).show();
}
but onBackPressed does not get called. How ever if I do not override onBackPressed, the application closes, when I press the backbutton and if I do override it it doesn't.
The rest of my activity looks like this:
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private Drawer drawer;
private FloatingActionButton fab_test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab_test = (FloatingActionButton) findViewById(R.id.fab_test);
fab_test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"FAB Test pressed",Toast.LENGTH_SHORT).show();
}
});
buildDrawer();
getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer,page).commit();
}
#Override
public void onBackPressed() {
Log.d("MainActivity","onBackPressed");
Toast.makeText(getApplicationContext(),"onBackPressed",Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
}
EDIT: I'm talking about the hardware-backbutton(not the actionbar one)

This question is already answered, but I feel to clear something here in this topic. Most comments and answeres point out to use super.onBackPressed() and that this is the cause of the not working method onBackPressed(). But that is not correct and important to let other beginners know. The method onBackPressed() does not need to use super.onBackPressed() . onBackPressed()also works if somebody, for example, comment super.onBackPressed() out.
As the questionier has written, he won´t use super.onBackPressed() because it will close the activity. So, the cause of this why it isn´t working, could be seperated into three possible causes:
The Log doesn´t work because of a wrong filter in the logcat console
The Toast dosn´t work because of the wrong passed context
The OS is implemented wrong by the supplier.
Usually, the toast works by passing the correct context. In the case of questioner, simply passing this .
#Override
public void onBackPressed() {
Log.d("MainActivity","onBackPressed");
Toast.makeText(this,"onBackPressed",Toast.LENGTH_SHORT).show();
}
For the Log, simply set the correct filter on logcat.
I don´t care if somebody give downvotes now, but it must be clear for other beginners, that super.onBackPressed() must not be used.
Anyway, the use of onKeyDown() also is a solution.

The onBackPressed() is a default action called from onKeyDown() in API < 5 and a default action called from onKeyUp() from API level 5 and up. If onKeyUp() does not call super.onKeyUp(), onBackPressed() will not be called.
Documentation onKeyDown()
Documentation onKeyUp().
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
/*
* without call to super onBackPress() will not be called when
* keyCode == KeyEvent.KEYCODE_BACK
*/
return super.onKeyUp(keyCode, event);
}
Also another reason that onBackPressed() may not be called is because you are using the soft back button on the actionbar, it that case the following is needed:
#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.
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

You are missing, super.onBackPressed();
#Override
public void onBackPressed() {
super.onBackPressed();
}
or you can use
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//replaces the default 'Back' button action
if(keyCode==KeyEvent.KEYCODE_BACK) {
// something here
finish();
}
return true;
}
thanks

make sure you are not calling onkeydown in your super view as it handles the back button clicking first.

working fine onKeyDown function return type false;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return false;
}

For whoever is wondering, as most functionality is deprected API 30>, the following will surely help you a lot.
public class MainActivity extends AppCompatActivity {
private OnBackPressedCallback onBackPressedCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onBackPressedCallback = new OnBackPressedCallback(true) {
#Override
public void handleOnBackPressed() {
// Your business logic to handle the back pressed event
Log.d(TAG, "onBackPressedCallback: handleOnBackPressed");
}
};
getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
}
}

Just Remove super.onBackPressed() it will work

Related

onEditActionListener android defined

I have been getting into the android app world as of late. I understand that you want to place what variables you can into the onCreate method so that you can start using your variables right away. However, I am at a loss for a part of my code where I need to define onEditActionListener's to listen for user input but then also once enter is pressed get their text and send it to another activity. My research has shown I want to define these using the EditText and onEditActionListeners. however, I am at a loss as to how to go about this. Do I need to create a class that extends onEditActionListener?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_horde_calculator);
EditText myText = (EditText) findViewById(R.id.numToSend);
OnEditorActionListener onEditorActionListener = new myClass();
myText.setOnEditorActionListener(onEditorActionListener);
}
that is a copy of my current code and I am unsure if this is the correct way to go about doing it. If I was to create a new onEditActionListener wouldn't that make my onCreate more complex than having a few lines of variables? I feel that there might be a more clear way of going about this. However, after looking through stack overflow I couldnt' seem to find something that made sense. I didn't want to just copy and paste code, but really understand how it all flows together.
Just another idea of how you can achieve this:
public class MainActivity extends AppCompatActivity implements TextView.OnEditorActionListener {
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
editText = (EditText) findViewById(R.id.numToSend);
editText.setOnEditorActionListener(this);
}
#Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL
&& event.getAction() == KeyEvent.ACTION_DOWN) {
//both attempt are the same
Log.d("onEditorAction", view.getText().toString());
Log.d("onEditorAction", editText.getText().toString());
}
return true;
}
}
Use TextView.OnEditorActionListener :
TextView.OnEditorActionListener listener = new TextView.OnEditorActionListener(){
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL
&& event.getAction() == KeyEvent.ACTION_DOWN) {
//call your new activity here
}
return true;
}
};
myText.setOnEditorActionListener(listener);

How to finish() an activity with SoftKeyboard visible with onBackPressed()

I have an activity where the whole screen is dedicated to sending one message. Being one EditText on the top half, and the SoftKeyboard always visible on the bottom half.
When i press back, the SoftKeyboard hides and i have to press back again to leave the activity.
The behavior that i'm struggling to get is : finishing the activity right away when i press the back button, instead of hiding the keyboard.
You can find this behavior in the twitter app for example, when writing a new tweet.
I tried with overriding the onBackPressed() function, but seems like when the keyboard is visible, the function is not called.
#Override
public void onBackPressed() {
finish();
}
Any help would be really appreciated!
So after trying many things, here something that worked :
Subclass EditText and override the onKeyPreIme() function to send a call back.
Here's the code for the subclass :
OnKeyPreImeListener onKeyPreImeListener;
public void setOnKeyPreImeListener(OnKeyPreImeListener onKeyPreImeListener) {
this.onKeyPreImeListener = onKeyPreImeListener;
}
#Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
if(onKeyPreImeListener != null)
onKeyPreImeListener.onBackPressed();
Log.d(TAG, "HIDING KEYBOARD");
return false;
}
return super.dispatchKeyEvent(event);
}
public interface OnKeyPreImeListener {
void onBackPressed();
}
Then in your activity for each of your TextView :
EditTextGraphee.OnKeyPreImeListener onKeyPreImeListener =
new EditTextGraphee.OnKeyPreImeListener() {
#Override
public void onBackPressed() {
Log.d(TAG, "CALL BACK RECEIVED");
MyActivity.this.onBackPressed();
}
};
editText.setOnKeyPreImeListener(onKeyPreImeListener);
new answer:
so apparently you don't receive the onBackPressed callback, but that doesn't mean you can't detect the keyboard closing.
Using the technique described here: How to check visibility of software keyboard in Android?
you can detect when the keyboard open/close, so when the keyboard closes you call finish();
deprecated, original answer:
simply override the back press event in the activity:
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
I assume that since the soft keyboard is visible probably an edittext has a focus. So you can catch the back pressed event by adding an OnEditorActionListener on that EditText and finish activity.
yourEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP){
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK){
finish();
}
}
return false;
}
});
You nee to extend EdtText class and implement onKeyPreIme method.
public class MyEditText extends EditText {
/* Must use this constructor in order for the layout files to instantiate the class properly */
public MyEditText(Context context, AttributeSet attrs)
{
super(context, attrs);
// TODO Auto-generated constructor stub
}
#Override
public boolean onKeyPreIme (int keyCode, KeyEvent event)
{
// do your stuff here.
return true;
}
}
Override onBackPressed() method like this :
#Override
public void onBackPressed() {
hideKeyboard();
finish();
}
For hideKeyboard() function please search in the Internet .

Android SDK (Eclipse) : How To Use SetOnKeyListener with Button?

I just don't know how to do it. The Code is so confusing for me. Can anyone please show me the code with explanation?
What I want is to assign enter keyCode to the btn button, so when user touches Enter SoftKey, the toast will show up just like clicking the button!
Here is The Simple App to use the code :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.btn);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "Hello World", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Please Explain it to me don't Just Write it , I'm New to Android , thanks for your Time
Well, you need to set OnKeyListener for your button similar way you already set OnClickListener:
b.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// your custom implementation
if (KeyEvent.KEYCODE_ENTER == keyCode) { // match ENTER key {
// show the toast
Toast.makeText(MainActivity.this, "Hello World",
Toast.LENGTH_SHORT).show();
return true; // indicate that we handled event, won't propagate it
}
return false; // when we don't handle other keys, propagate event further
}
});
Additional explanations are in the comments. Hope that helps

Android Activity: Listener for outside touch event

I have an Activity shown as a Dialog:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setTheme(android.R.style.Theme_Dialog);
setFinishOnTouchOutside(true);
}
When the user closes the Activity-Dialog by touching outside the Activity-Dialog window, the Activity finishes.
How can I set a Listener on this event?
This is important because I want to be able to call
setResult(intResultCode, intent);
right before finishing.
Calling setResult() in onPause() can be too late already.
why to struggle that much? just override finish() method in Avtivity...
#Override
public void finish() {
setResult(int resultCode, Intent data);
super.finish();
}
first put
dialog.setCanceledOnTouchOutside(true)
and after that use
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Rect dialogBounds = new Rect();
getWindow().getDecorView().getHitRect(dialogBounds);
if (!dialogBounds.contains((int) ev.getX(), (int) ev.getY())) {
// Tapped outside so we finish the activity
this.finish();
}
return super.dispatchTouchEvent(ev);
}
It's possible. You can override onTouchEvent()
#Override
public boolean onTouchEvent(MotionEvent event) {
if (MotionEvent.ACTION_OUTSIDE == event.getAction()) {
// Your logic
// return true if you don't want to pass event further
}
return super.onTouchEvent(event);
}
If you don't get ACTION_OUTSIDE event, possibly you need to add FLAG_NOT_TOUCH_MODAL and FLAG_WATCH_OUTSIDE_TOUCH window flags. Works for me without it.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
...
}

Trouble triggering onKey event with Android

I'm having difficulty getting my main View's onKey event to trigger. I'm not sure what I'm doing wrong, I have correctly implemented the onClick event but cannot seem to figure out the onKey event.
Here's the relevant code:
public class MyActivity extends Activity {
private RelativeLayout main;
private ApplicationToolbar toolbar;
public void onCreate(Bundle savedInstanceState) {
...
this.main = (RelativeLayout) this.findViewById(R.id.main);
this.toolbar = new ApplicationToolbar(this);
// toolbar is added to main later on in the code...
this.main.setOnClickListener(mClickListener);
this.main.setOnKeyListener(mKeyListener);
}
private OnClickListener mClickListener = new OnClickListener() {
public void onClick(View v) {
toolbar.setVisibility(View.VISIBLE); // Works correctly.
}
};
private OnKeyListener mKeyListener = new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
toolbar.setBackgroundColor(0xFF0000FF); // Does not work.
return true;
}
};
}
In fact, no matter what code I put within mKeyListener it does not execute, which leads me to believe that the event itself is never being triggered, even when I pressed a bunch of keys on my physical keyboard (Motorola Droid, Android 2.1).
You can try overriding onKeyDown(int keyCode, KeyEvent event)
Check:
Back and other hard keys: three stories
is there a default back key(on device) listener in android?

Categories

Resources