Multiple KeyEvents? - java

Hi I have a problem with my Android app. I use a boolean method to change the function of the back button to make a layout change. As shown in the code if I use a if- statement and if these things are true, the layout changes. The problem is I have more than one point with different situations where I would like to modify the function of the button. But if I copy the function and change the name eclipse wants to remove the # override, and then the method no longer works.
So now the question is: How can I create multiple KeyEvents?
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && lengthisopen == true){
lengthisopen = false;
setContentView(R.layout.length);
return true;
}
return super.onKeyDown(keyCode, event);
}
public boolean onKeyDown2(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && lengthisopen == true){
lengthisopen = false;
setContentView(R.layout.length);
return true;
}
return super.onKeyDown(keyCode, event);
}

onKeyDown(int keyCode, KeyEvent event) is a method available is Activity, So you can override it. But onKeyDown2() is not a super class's method. So you can't override it from any of the super classes. That's why it said you to remove #override.
If you want to create multiple key events then you should go to only
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && lengthisopen == true){
lengthisopen = false;
setContentView(R.layout.length);
return true;
}
else if(condition){
// next code
}
return super.onKeyDown(keyCode, event);
}

Related

Submit an AlertDialog.Builder containing an EditText by pressing enter on the keyboard in android studio

This is my code for an AlertDialog.Builder that has a custom view with an EditText. After entering the value inside the EditText, I want the press of Enter on the keyboard to act the same way as the PositiveButton of the AlertDialog.Builder. I have included the necessary 'imeOptions' part in the XML file. I manage to execute the code when pressing Enter, but the AlertDialog.Builder is still on screen and does not dismiss like when the PositiveButton on the AlertDialog.Builder is clicked.
//AlertDialog to set weekly income
incomeAlert = new AlertDialog.Builder(this);
incomeInflater = this.getLayoutInflater();
incomeDialogView = incomeInflater.inflate(R.layout.activity_weekincome, null);
incomeAlert.setView(incomeDialogView);
et_WeekIncome = incomeDialogView.findViewById(R.id.ls_WeekIncome);
et_WeekIncome.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
submitIncome();
return true;
}
return false;
}
});
incomeAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
submitIncome();
}
});
Thanks in advance for any help.
UPDATE: I managed to dismiss the AlertDialog.Builder by adding another piece of code as shown below
AlertDialog incomeDialog = incomeAlert.create();
incomeDialog.show();
Then when needing to dismiss, I use
incomeDialog.dismiss();
Since dismiss() is not available with AlertDialog.Builder, I had to create the Builder through an AlertDialog. Then I call dismiss() on the AlertDialog.
Thank you all for your input.
You can use OnKeyListener with your edit text to handle a specific keypress.
mEditTV.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
// do action
return true;
}
return false;
}
});
You can use the above setOnKeyListener this way.
et_WeekIncome.setOnKeyListener(new OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_ENTER:
submitIncome();
return true;
default:
break;
}
}return false;
}
});
Since dismiss() is not available with AlertDialog.Builder, I had to create the Builder through an AlertDialog. Then I call dismiss() on the AlertDialog.
There is another way to deal with this problem: use the setOnShowListener callback to set the key listener. This gives you access to the dialog's dismiss() method.
incomeAlert.setOnShowListener((DialogInterface d) -> {
et_WeekIncome.setOnKeyListener((v, keyCode, event) -> {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER) {
onClick(dialog, BUTTON_POSITIVE);
d.dismiss();
return true;
}
return false;
});

setOnKeyListener function works on some phones but not on others

So i have a function that's supposed to listen for the enter key to be pressed and then hide the keyboard but when i tested it works on one device but not another.
My function:
notes.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_DOWN) {
return false;
}
if (keyCode == KeyEvent.KEYCODE_ENTER) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getRootView().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return true;
}
return false;
}
});
Works on one phone running Android 8.1 But not on my other phone running Android 8.0
What could possibly be causing this?

background button press detection

I am trying to build an android app which detects button pressed on a background and plays a sound or something. For demo, I am trying to add this method
public boolean onKeyDown(int keyCode, KeyEvent event) {
final MediaPlayer abc = MediaPlayer.create(this, R.raw.abc);
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
abc.start();
}
return super.onKeyDown(keyCode, event);
}
to this class
public class RSSPullService extends IntentService{
public RSSPullService(){
super("Nevermind me");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
}
}
Is there something that can be helpful? I am new to android development and Java.
In touch android mobile phones there is not any keyboard hardware. So please specify which button you want to get pressed?
Edited:
Add the following permission in Manifest fie:
<uses-permission android:name="android.permission.PREVENT_POWER_KEY" />
and override following methods:
//To capture any short click of button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
// this is method which detect press even of button
event.startTracking(); // Needed to track long presses
return true;
}
return super.onKeyDown(keyCode, event);
}
//To capture long press of power button
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
// Here we can detect long press of power button
return true;
}
return super.onKeyLongPress(keyCode, event);
}

Stop keyboard from closing when Enter is pressed in EditText?

I have an EditText which has the singleLine attribute set to true. When I press Enter on the keyboard, the keyboard is hidden. Is it possible to prevent this?
I've been using OnKeyListener which caused this problem. Switching to OnEditorActionListener stops the Keyboard from closing when pressing Enter and allows me to have full control of it.
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_DONE) {
//DO THINGS HERE
return true;
}
return false;
}
});
this should help you
youredittext.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keyCode, KeyEvent event) {
if ( (event.getAction() == KeyEvent.ACTION_DOWN ) &&
(keyCode == KeyEvent.KEYCODE_ENTER) )
{
// hide virtual keyboard
InputMethodManager imm =
(InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInputFromInputMethod(edittext.getWindowToken(), 0);
return true;
}
return false;
}
});
when you press the enter key the inputMethodManager will show the keyboard, if needed.
hope this will solve your problem :)
edit:
if this will not work try use the event.getKeyCode() in the secend part of the if statment
edit II: sorry, i read it wrong, i fixed it now try this one.

How to exit an infinite while loop when user taps screen?

I currently have a while loop that starts when a user taps the screen. The loop is meant to be infinite, and should stop when it senses another screen tap from the user. (And, if tapped again, it'll start looping again, etc.) I’ve tried to break the loop in two different ways, with both yielding non-satisfactory results:
METHOD 1: When I try this method, what happens is that the user taps, the loop starts. The user taps again, and that tap doesn't get registered and the loop just keeps on going.
boolean playing = false;
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
if(!playing)
{
playing = true;
while(playing)
{
//do something here
}
}
else if(playing)
{
playing = false;
}
}
return false;
}
METHOD 2: When I try this method, what happens is that the user taps, the loop starts, goes through one iteration, then stops.
boolean playing = false;
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
if(!playing)
{
playing = true;
whileLoop:
while(playing)
{
//do something here
}
}
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
playing = false;
break whileLoop;
}
}
return false;
}
I've looked at these questions, but neither helped me with my specific situation:
How do I exit a continuous while loop by some user input?
How to exit an infinite while loop using user input?
So how do I implement this while loop? I just want a simple interface where a user's tap would toggle the while loop on/off.
Put the infinite loop within a Thread. Having it there, you can just have a control variable inside (like playing), and once tap again and you want to stop, simply set it to false. The Thread, running paralelly, will be able to handle both events (the tap and the Thread stop).
---- EDIT ----
Example added:
// You'd probably need to store this variable class-wide,
// so you can control when the user has tapped for the first or second time
boolean playing = false;
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
if(!playing)
{
playing = true;
new Thread(
new Runnable() {
public void run() {
while(playing)
{
//do something here
}
}
}
).start();
}
else if(playing)
{
playing = false;
// As you're controlling the playing value in the Thread,
// setting it here to false would mean that your thread stops too.
}
}
return false;
}
try this:
boolean playing = false;
Handler handler = new Handler();
Runnable runner = new Runnable() {
#Override
public void run() {
// do something here
handler.post(this);
}
};
imageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
if(!playing) {
playing = true;
runner.run();
return true;
}
if(playing) {
playing = false;
handler.removeCallbacks(runner);
handler = null;
runner = null;
Toast.makeText(context, "NO", Toast.LENGTH_SHORT).show();
return true;
}
}
return false;
}
});

Categories