How to implement onKeyDown in Fragment - java

I change all my activitys to Fragment. I got stuck in the onkeydown part.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (!sector.getText().toString().equals("Sector") && (media.isChecked() || completa.isChecked())) {
siguiente.setEnabled(true);
} else {
siguiente.setEnabled(false);
}
return super.onKeyDown(keyCode, event);
}

You can do this by defining method in your fragment class. For example:
public void onMyKeyDown(int key, KeyEvent event){
//define your statement like
if (Integer.parseInt(android.os.Build.VERSION.SDK) > 5
&& key == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Do you really want to Exit?")
.setIcon(R.drawable.logo)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}})
.setNegativeButton(android.R.string.no, null).show();
}
}
Call onMyKeyDown method whenever a key-down event is raised in your Activity class. example:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//call fragment method onMyKeyDown(keyCode, event)
return super.onKeyDown(keyCode, event);
}

Related

Im not Getting the Button Release Toast in OnTouchListners

The issue is im not getting the Button release Toast.
i've a simple view in xml on which im performing onTouch.
hidenBtn.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getActionMasked();
if (action == MotionEvent.ACTION_DOWN) {
firstTime=System.currentTimeMillis();
Toast.makeText(MainActivity.this, "Pressed", Toast.LENGTH_SHORT).show();
} else if (action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_CANCEL) {
Toast.makeText(MainActivity.this, "Released", Toast.LENGTH_SHORT).show();
secondTime=System.currentTimeMillis();
if(secondTime-firstTime>=5000){
//do your actions here,prev,curr are fields in a class
ShowDialog();
}
else{
firstTime=0;
secondTime=0;
}
}
// TODO Auto-generated method stub
return false;
}
});
Change your OnTouchListener like this:
hidenBtn.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getActionMasked();
if (action == MotionEvent.ACTION_DOWN) {
firstTime=System.currentTimeMillis();
Toast.makeText(MainActivity.this, "Pressed", Toast.LENGTH_SHORT).show();
return true;
} else if (action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_CANCEL) {
Toast.makeText(MainActivity.this, "Released", Toast.LENGTH_SHORT).show();
secondTime=System.currentTimeMillis();
if(secondTime-firstTime>=5000){
//do your actions here,prev,curr are fields in a class
ShowDialog();
}
else{
firstTime=0;
secondTime=0;
}
}
// TODO Auto-generated method stub
return false;
}
});
You are returning false at ACTION_DOWN which means you are not consuming your touch event, so no other steps of the same event are triggered. Therefore you need to return true in the ACTION_DOWN so you can intercept ACTION_UP.

Back button press twice before quitting app

How can I configure the back button to be pressed twice before the app exits? I want to trigger
#Override
public void onBackPressed() {
//custom actions
//display toast "press again to quit app"
super.onBackPressed();
}
Try this:
private boolean doubleBackToExitPressedOnce = false;
#Override
protected void onResume() {
super.onResume();
// .... other stuff in my onResume ....
this.doubleBackToExitPressedOnce = false;
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press twice to exit", Toast.LENGTH_SHORT).show();
}
This snippet handle also the reset state when the activityis resumed
I see this question is a bit old but I though this might help some people looking for an alternative to the answers already given.
This is how I handle backing out of my applications. If someone has a better -- or a Google suggested -- method of accomplishing this I'd like to know.
Edit -- Forgot to mention this is for Android 2.0 and up. For previous versions override onKeyDown(int keyCode, KeyEvent event) and check for keyCode == KeyEvent.KEYCODE_BACK. Here is a good link to check out.
private boolean mIsBackEligible = false;
#Override
public void onBackPressed() {
if (mIsBackEligible) {
super.onBackPressed();
} else {
mIsBackEligible = true;
new Runnable() {
// Spin up new runnable to reset the mIsBackEnabled var after 3 seconds
#Override
public void run() {
CountDownTimer cdt = new CountDownTimer(3000, 3000) {
#Override
public void onTick(long millisUntilFinished) {
// I don't want to do anything onTick
}
#Override
public void onFinish() {
mIsBackEligible = false;
}
}.start();
}
}.run(); // End Runnable()
Toast.makeText(this.getApplicationContext(),
"Press back once more to exit", Toast.LENGTH_SHORT).show();
}
}
You could do what you're asking with a global integer and just count it, if > 2, quit.
But you could take a better (IMO) approach, where you question the user if they would like to quit or not:
private void questionQuit(){
final CharSequence[] items = {"Yes, quit now", "No, cancel and go back"};
builder = new AlertDialog.Builder(mContext);
builder.setCancelable(false);
builder.setTitle("Are you sure you want to quit?");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item){
case 0:
quit();
break;
case 1:
default:
break;
}
}
}).show();
AlertDialog alert = builder.create();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK :
int i = 0 ;
if(i == 1 )
{
finish();
}
i++;
return true;
}
}
return super.onKeyDown(keyCode, event);
}

Android keyboard on hold

i've been trying to create an "onHold" action on the enter key of the keyboard.
searchField.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
searchField.setText(searchField.getText().toString().replace("\n", ""));
if((CounterRunning)&&(event.getAction() == KeyEvent.ACTION_UP ) && (keyCode == KeyEvent.KEYCODE_ENTER))
{
CounterRunning = false;
counter.cancel();
AddItem();
}
if((event.getAction() == KeyEvent.ACTION_DOWN ) && (keyCode == KeyEvent.KEYCODE_ENTER))
{
CounterRunning = true;
counter.start();
}
}});
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
CounterRunning = false;
AskForDate();
}
#Override
public void onTick(long millisUntilFinished) {
}
}
i want the user to run AddItem() on click and run AskForDate() if the user hold on the enter key.
but the action KeyEvent.ACTION_DOWN is only triggering when i remove the finger from the keyboard, am i missing something? tested on android 2.3.7 (CM7.2) and android 4.0.4 (CM9), both with default softkeyboard
onKeyLongPress event
try the upper one, it says you must call startTracking in your listener
so your code should be like
if((event.getAction() == KeyEvent.ACTION_DOWN ) && (keyCode == KeyEvent.KEYCODE_ENTER))
{
event.startTracking();
}
and since Activity subclasses KeyEvent.Callback you can directly call your AskForDate() from there.

Android How to listen for Volume Button events?

I know you guys are probably tired of these kinds of posts, but why doesn't anything happen when I press volume down? I'm just trying to make a simple code, but apparently it's not working.
package com.cakemansapps.lightwriter;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;
import android.view.KeyEvent;
import android.util.Log;
public class LightWriter extends Activity implements OnTouchListener {
private static final String TAG = "Touch" ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
}
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
Log.w("LightWriter", "I WORK BRO.");
return true;
}
return super.onKeyLongPress(keyCode, event);
}
public boolean onTouch(View view, MotionEvent me) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
I don't know if you can get long press events for the hardware keys.
I've used this code to listen for the volume button before.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
// Do something
}
return true;
}
If that doesn't work for you let us know what device you are testing on.
Kotlin
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
// Do something
}
return true
}
Another approach
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
// ... your code
return true;
} else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)) {
// ... your code
return true;
} else
return super.onKeyDown(keyCode, event);
}
try these. just tested them:
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
super.onKeyLongPress(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
Log.w("LightWriter", "I WORK BRO.");
return true;
}
return false;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
Log.w("LightWriter", "I WORK BRO.");
return true;
}
return true;
}
use this code to handle Volume key event
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
super.onKeyUp(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
Toast.makeText(MainActivity.this,"Up working",Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
Toast.makeText(MainActivity.this,"Down working",Toast.LENGTH_SHORT).show();
return true;
}
return false;
}

Syntax error on token "if", invalid AnnotationName

Hi I am working with android and I'm trying to put an "if" statement around this class but I get the error "Syntax error on token "if", invalid AnnotationName"
Any help?
private String str = "0";
if(str == 0){
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK)
{
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Coupon")
.setMessage("Do you want a coupon texted to you?")
.setPositiveButton("YES!", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//Stop the activity
Toast.makeText(buttonOne.this, "Great! You'll get one in just a couple of minutes.", Toast.LENGTH_LONG).show();
finish();
}
})
.setNegativeButton("Not now", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//Stop the activity
finish();
}
})
.show();
return true;
}
else
{
return super.onKeyDown(keyCode, event);
}
}
}
else
{}
You can't put control structures (like if statements) outside a function.
you must use equals String method:
if (str.equals("0")){
...
}

Categories