show alertdialog while i press the screen - java

i have a list with surveys and all those surveys contains a picture. when you finish a survey the app returns to the overview where i can see all completed and all uncompleted surveys and all rejected surveys.
What i want:
Now if i click long on the screen and the survey isnt rejected and is completed i want to get a preview of the picture as long as i press the screen and disappear if i release the screen.
The problems are:
How can i cancel or dismiss a AlertDialog without adding a positive
Button?
Is it possible to get the MotionEvent without an onTouch Listener and
just with longClickListener?
Here is my code with an onTouch and a longClick-listener and i want to eliminate one of them:
row.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
row.setOnLongClickListener(l -> {
// V3.0 only execute long click if the survey hasn't been declined
if (getContext() instanceof SurveyListPatientActivity && !erhebung.rejected() && !erhebung.isCompleted()) {
((SurveyListPatientActivity) getContext()).showRejectSurvey(erhebung);
}else if(getContext() instanceof SurveyListPatientActivity && !erhebung.rejected() && erhebung.isCompleted()){
AlertDialog.Builder adb = new AlertDialog.Builder(getContext());
ImageView imageView = new ImageView(getContext());
byte[] bytes = Base64.decode(erhebung.getPic(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
imageView.setImageBitmap(bitmap);
imageView.setPadding(10,10,10,10);
adb.setView(imageView);
adb.create().show();
if (event.getAction() == MotionEvent.ACTION_UP){
// cancel AlertDialog
}
}
return true;
});
return false;
}
});
Thank you very much!
EDIT:
Whit the help of #brianoqr i changed my code into this.
Everything works fine but the Dialog dosent disappear.
row.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(getContext());
ImageView imageView = new ImageView(getContext());
byte[] bytes = Base64.decode(erhebung.getPic(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
imageView.setImageBitmap(bitmap);
imageView.setPadding(10,10,10,10);
adb.setView(imageView);
dialog = adb.create();
dialog.show();
isLongPressed = true;
return true;
}
});
row.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.onTouchEvent(event);
System.out.println("1");
if (event.getAction() == MotionEvent.ACTION_UP) {
System.out.println("2");
if (isLongPressed) {
dialog.cancel();
System.out.println("canceld");
isLongPressed = false;
}
}
return false;
}
});

I probably would do it differently, but to answer the question how to cancel a dialog with out a button:
AlertDialog dialog = adb.create();
dialog.show()
if (event.getAction() == MotionEvent.ACTION_UP){
dialog.dismiss()
}
The code you have written will not work as you want, the onlongpress is the leading action, you can structure your code something like in this ticket: Android - Detect End of Long Press
And your dialog will then need to be in a different scope to allow for automatic dismissal
EDIT
row.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if(!isLongPressed){
isLongPressed = true;
AlertDialog.Builder adb = new AlertDialog.Builder(getContext());
ImageView imageView = new ImageView(getContext());
byte[] bytes = Base64.decode(erhebung.getPic(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
imageView.setImageBitmap(bitmap);
imageView.setPadding(10,10,10,10);
adb.setView(imageView);
dialog = adb.create();
dialog.show();
}
return true;
}
});
row.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.onTouchEvent(event);
System.out.println("1");
if (event.getAction() == MotionEvent.ACTION_UP) {
System.out.println("2");
if (isLongPressed) {
dialog.cancel();
System.out.println("canceld");
isLongPressed = false;
}
}
return false;
}
});

Related

How to make a button Touchable with onTouchListener?

I have a Button that I have tried to make touchable so when I hold it down it moves an ImageView constantly for the amount of time it is held down, but instead, it only moves the ImageView once each time I press it.
final ImageView box = (ImageView) findViewById(R.id.box);
currentX = (int) box.getX();
Button rightarrow = (Button) findViewById(R.id.right);
rightarrow.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, final MotionEvent e) {
v.performClick();
if (e.getAction() == MotionEvent.ACTION_DOWN) {
v.setPressed(true);
handlerRight.postDelayed(new Runnable() {
#Override
public void run() {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
currentX += 5;
box.setX(currentX);
handlerRight.postDelayed(this, 100);
} else {
}
}
}, 0);
} else {
v.setPressed(false);
}
return false;
}
});
In that new Thread that you run there, you need to create a while loop that will run while the button is pressed. In that while loop, just move the image. Here is the code:
final ImageView box = (ImageView) findViewById(R.id.box);
currentX = (int) box.getX();
Button rightarrow = (Button) findViewById(R.id.right);
rightarrow.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, final MotionEvent e) {
v.performClick();
if (e.getAction() == MotionEvent.ACTION_DOWN) {
v.setPressed(true);
handlerRight.postDelayed(new Runnable() {
#Override
public void run() {
while (v.isPressed()){
currentX += 5;
box.setX(currentX);
//handlerRight.postDelayed(this, 100);
}
}
}, 0);
} else {
v.setPressed(false);
}
return false;
}
});
Note: I'm not sure where that
handlerRight.postDelayed(this, 100);
is supposed to be because I'm not familiar with it so you just put it. But this is it I hope!

Keep user logged in but exit android app on double pressing back

I am using Firebase to sign in the user and have implemented the code to exit the app on double click. But the problem is the same screen is popping up again.
I tried a workaround setting a SharedPreference and then checking that in mAuthListner. But it did not work.
Here are the relevant sections of the code:
mAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
SharedPreferences d= getSharedPreferences("backPressed", Context.MODE_PRIVATE);
Boolean t = d.getBoolean("back",false);
if (firebaseAuth.getCurrentUser() != null && !t) {
startActivity(new Intent(MainActivity.this, Second.class));
}
if (t) {
d.edit().putBoolean("back",false);
}
}
};
Code for back button pressed:
boolean doubleBackToExitPressedOnce = false;
private Handler mHandler = new Handler();
private final Runnable mRunnable = new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
};
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
SharedPreferences d= getSharedPreferences("backPressed",Context.MODE_PRIVATE);
d.edit().putBoolean("back",true);
finish();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
mHandler.postDelayed(mRunnable, 2000);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mHandler != null) { mHandler.removeCallbacks(mRunnable); }
}
How can I exit the app on back pressed twice while keeping the user logged in?
This is not a Firebase issue as Firebase will not log out until you specifically call the "Log Out" method.
You do not need SharedPreferences. Just set an Activity level variable BackOnce to False then set it in the OnBackPressed as necessary.
boolean BackOnce = false;
#Override
public void onBackPressed() {
if (BackOnce) {
finish();
} else {
BackOnce = true;
Snackbar sb = Snackbar.make(myView, "Press back again to close app", Snackbar.LENGTH_SHORT);
sb.addCallback(new Snackbar.Callback() {
#Override
public void onDismissed(Snackbar snackbar, int event) {
super.onDismissed(snackbar, event);
BackOnce = false;
}
});
sb.show();
}
}

setPressed is not working

I have this in my code and the .setPressed doesn't work:
Button btndesligado = (Button) findViewById(R.id.button12);
btndesligado.setOnClickListener(new OnClickListener() { //Botão para pôr silêncio!
#Override
public void onClick(View v) {
btndesligado.setPressed(true);
som = false;
vibrar = false;
}
});
What is wrong? It doesn't give me any error, it just doesn't work when I open it and click it. It was suposed to be pressed after I press once.
Android is changing the setPressed both before and after your onClickEvent
so change your code this code
btndesligado.setOnClickListener(new OnClickListener() { //Botão para pôr silêncio!
#Override
public void onClick(View v) {
btndesligado.setPressed(true);
som = false;
vibrar = false;
}
});
to this
btndesligado.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// show interest in events resulting from ACTION_DOWN
if (event.getAction() == MotionEvent.ACTION_DOWN) return true;
// don't handle event unless its ACTION_UP so "doSomething()" only runs once.
if (event.getAction() != MotionEvent.ACTION_UP) return false;
btndesligado.setPressed(true);
som = false;
vibrar = false;
return true;
}
});
It seems nothing wrong with your codes, It's working as you did, It sets the View's internal state to "pressed", or false to reverts the View's internal state from a previously set "pressed" state. And you've put that inside onClick of button means it acts only after you press the button,
If you want it pressed or revert then do like this,
Button btndesligado = (Button) findViewById(R.id.button12);
btndesligado.setPressed(true);
btndesligado.setOnClickListener(new OnClickListener() { //Botão para pôr silêncio!
#Override
public void onClick(View v) {
som = false;
vibrar = false;
}
});
Try this way.
btndesligado.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btndesligado.setPressed(true);
som = false;
vibrar = false;
}
});

Android Prompt Dialogue Box Upon Event Triggered

I am having some logic problem with my Java code to prompt dialogue box. So basically when my ratingBar is onTouch, I will get the star rate and prompt dialogue box:
ratingBar.setOnTouchListener(new OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
float touchPositionX = event.getX();
float width = ratingBar.getWidth();
float starsf = (touchPositionX / width) * 5.0f;
starRate = (int)starsf + 1;
ratingBar.setRating(starRate);
promptSubmitStar();
return true;
}
});
public void promptSubmitStar(){
AlertDialog.Builder Dialog = new AlertDialog.Builder(getActivity());
Dialog.setTitle("Confirm Rating");
LayoutInflater li = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = li.inflate(R.layout.option_submit_star, null);
txtPromptStarRate = (TextView) dialogView.findViewById(R.id.txtPromptStarRate);
txtPromptStarRate.setText("Confirm to submit " + starRate + " stars for this event?");
Dialog.setView(dialogView);
Dialog.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.dismiss();
}
});
Dialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.dismiss();
}
});
Dialog.show();
}
But with these codes, when user selected the star rate, the dialogue box prompted twice. I wonder which part is causing it. Thanks in advance.
It's because onTouch listener is called multiple times, i.e. when your finger lands on the screen (ACTION_DOWN) and when you move your finger up (ACTION_UP).
You want to show the dialog when the latter one fires:
ratingBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
float touchPositionX = event.getX();
float width = ratingBar.getWidth();
float starsf = (touchPositionX / width) * 5.0f;
starRate = (int) starsf + 1;
ratingBar.setRating(starRate);
promptSubmitStar();
}
return true;
}
});
I'm not sure why you'd use a touch listener though. You can listen to the RatingBar changes like this:
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar bar, float rating, boolean user) {
promptSubmitStar();
}
});

Start and stop recording with button click

I'm making a simple android app for recording sound. I have a startRecording() and stopRecording() methods. Now I implemented a ToggleButton named "Touch to record" so as you can already imagine, when the button is checked, you have to hold the record button to record sound and when the button is on "off" you have to click to start and then click to stop.
This is the current code:
touchToRecord.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked)
{
recBtn.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
recBtn.setImageResource(com.whizzappseasyvoicenotepad.R.drawable.record_btn_pressed);
chTimer.start();
chTimer.setTextColor(Color.GREEN);
startRecording();
}
else if (event.getAction() == MotionEvent.ACTION_UP)
{
recBtn.setImageResource(com.whizzappseasyvoicenotepad.R.drawable.record_btn);
chTimer.stop();
stopRecording();
nameAlert();
}
return true;
}
});
}
else
{
//onClickListener
}
}
});
Now I'm not sure how to make the onClickListener. If I try to do it like this:
recBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
It won't work because it underlines setOnClickListener and says:
The method setOnClickListener (View.OnClickListener) in the type View is not applicable for the arguments (new DialogInterface.OnClickListener(){})
Also, one more thing after I get this working; how do I check if the method is already running with if statement? I want to do something like this:
if (startRecording == isRunning)
{
stopRecording();
}
You could try android toggle button. Please see more information on:
http://developer.android.com/guide/topics/ui/controls/togglebutton.html
Solved the problem!
I avoided using onClickListener by setting onClick in XML and then just creating the method. Here's the code:
public void recordBtnClick(View v){
final ToggleButton touchToRecord = (ToggleButton)findViewById(R.id.tBtn1);
final ImageButton recBtn = (ImageButton) findViewById(com.whizzappseasyvoicenotepad.R.id.recButton);
if (touchToRecord.isChecked() == false)
{
if (recorder == null)
{
recBtn.setImageResource(com.whizzappseasyvoicenotepad.R.drawable.record_btn_pressed);
chTimer.start();
chTimer.setTextColor(Color.GREEN);
startRecording();
}
else if (recorder != null)
{
recBtn.setImageResource(com.whizzappseasyvoicenotepad.R.drawable.record_btn);
chTimer.stop();
stopRecording();
nameAlert();
}
}
else
{
//DO NOTHING
}
}

Categories

Resources