Buttons text gets cleared when i press it - android

I am currently making an app where i have a list for request to needs to be marked as finished and another list for the items inside the request. If I select a request, the items inside it will show in the items list and buttons with actions to perform for that items. But when I choose another request and press a button, the text on the button gets cleared. I am using sdk 26 on the project. It seems that the text is not displayed but the text value is still there after I tried to see if the text value of the button is still there.
EDIT:
This is the part where I initialize the views.
btnCustomerInfo = findViewById(R.id.btnCustomerInfo);
btnRemoveDiscount = findViewById(R.id.btnRemoveDiscount);
btnClear = findViewById(R.id.btnClear);
btnPay = findViewById(R.id.btnPay);
btnPrintBill = findViewById(R.id.btnPrintBill);
btnUpdate = findViewById(R.id.btnUpdate);
EDIT:
This is the relevant xml code.
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/btnCustomerInfo"
style="#style/AppTheme.Button"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Customer Info" />
<Button
android:id="#+id/btnRemoveDiscount"
style="#style/AppTheme.Button"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Remove Discount" />
<Button
android:id="#+id/btnClear"
style="#style/AppTheme.Button"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Clear" />
<Button
android:id="#+id/btnPay"
style="#style/AppTheme.Button"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Pay" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/btnPrintBill"
style="#style/AppTheme.Button"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Print Bill" />
<Button
android:id="#+id/btnTransfer"
style="#style/AppTheme.Button"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Transfer" />
<Button
android:id="#+id/btnMerge"
style="#style/AppTheme.Button"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Merge" />
<Button
android:id="#+id/btnUpdate"
style="#style/AppTheme.Button"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Update" />
</TableRow>
EDIT: This is my AppTheme.Button
<style name="AppTheme.Button" parent="AppTheme">
<item name="colorAccent">#ebebea</item>
<item name="android:textColor">#color/black</item>
</style>
I am not setting any value of button in the onClick
EDIT: Button onClicks
btnCustomerInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "btnTxt: "+((Button) view).getText());
showCustomerInfoDlg(ip);
}
});
btnRemoveDiscount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MaterialDialog.Builder mDlgBuild = new MaterialDialog.Builder(ctx);
mDlgBuild.title("Discount");
mDlgBuild.content("Remove discount on " + acOr.getTableName() + " " + acOr.getTableNum() + "(" + acOr.getSessionBundle() + ")" + "?");
mDlgBuild.cancelable(false);
mDlgBuild.positiveText("Ok");
mDlgBuild.negativeText("Cancel");
mDlgBuild.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
dialog.dismiss();
Progress_dialog("Removing discount ...");
progressDlg.show();
}
});
mDlgBuild.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
dialog.dismiss();
}
});
mDlgBuild.show();
}
});
for btnTransfer:
final MaterialDialog mDlg = new MaterialDialog.Builder(MainActivity.this)
.customView(R.layout.dlg_transfer_table,true)
.cancelable(false)
.negativeText("Cancel")
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
dialog.dismiss();
}
}).show();
TextView lblTableNum = (TextView)mDlg.findViewById(R.id.lblDlgTransferTableNumber);
TextView lblCustomerName = (TextView)mDlg.findViewById(R.id.lblDlgTransferCustomerName);
RecyclerView lstTable = (RecyclerView)mDlg.findViewById(R.id.lstDlgTransferTableList);
The other buttons do printing, opens a webview, remove items on the list for the items inside the request, and shows another button. Even if the buttons still doesn't have code in it, clicking it still removes the text on the buttons display.
EDIT: Gif
EDIT: this are the code of the two buttons
Pay button:
final MaterialDialog mDlg = new MaterialDialog.Builder(MainActivity.this)
.title("Payment Options")
.customView(R.layout.dlg_pay_option,true)
.cancelable(false).show();
Button btnCash = (Button)mDlg.findViewById(R.id.btnDlgPayOptionCash);
Button btnCard = (Button)mDlg.findViewById(R.id.btnDlgPayOptionCard);
Button btnOther = (Button)mDlg.findViewById(R.id.btnDlgPayOptionOther);
Button btnCancel = (Button)mDlg.findViewById(R.id.btnDlgPayOptionCancel);
Button btnRemovePayment = (Button)mDlg.findViewById(R.id.btnDlgPayOptionRemovePayment);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDlg.dismiss();
}
});
btnCash.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDlg.dismiss();
typeOfPayment = "cash";
CashPayment();
}
});
btnCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDlg.dismiss();
typeOfPayment = "card";
CardPayment();
}
});
btnOther.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDlg.dismiss();
typeOfPayment = "other";
OtherPayment();
}
});
Update button:
Intent i = new Intent(MainActivity.this, UpdateOrder.class);
i.putExtra("or_id", acOr.getSessionBundle());
i.putExtra("cust_name", acOr.getCustomerName());
i.putExtra("table_num", acOr.getTableNum());
startActivity(i);
finish();
At first, I already selected an item on the right then clicked pay. Next, I selected another item on the right and clicked pay. Then I clicked cancel on the dialog. Lastly, I clicked the update button.

There's a good chance that the text is not cleared but has the background color in a certain state. To deal with it, you can create a color state list and set it in the android:textColor attribute.

Related

Button not responding XML issue?

I was working yesterday and not today. Have two buttons one to go back, one that is an emergency button that calls a method to open the dialer for a call to the ambulance.
I think it may be an XML problem not sure was working fine now unresponsive maybe I changed something I shouldn't have. When it was clicking earlier it was saying the method could not be found which I just don't get it as it is in the correct file
ReportActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//allows for a smoother transition
overridePendingTransition(0, 0);
setContentView(R.layout.activity_report);
EditText incidentReport = this.findViewById(R.id.Incident_Report);
incidentReport.setSelection(0);
try {
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ReportActivity.this, MainActivity.class);
startActivity(intent);
}
});
} catch (NullPointerException n) {
Toast.makeText(this, "Error,", Toast.LENGTH_LONG);
}
try {
emergency.setOnClickListener(new View.OnClickListener() {
public void onClick(#NonNull View v) {
Intent call = new Intent(ReportActivity.this, CallActivity.class);
startActivity(call);
}
});
} catch (NullPointerException n) {
Toast.makeText(this, "Error,", Toast.LENGTH_LONG);
}
}
#Override
public void onClick(View v) {
}
private boolean checkPermission(String permission) {
int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
return (permissionCheck == PackageManager.PERMISSION_GRANTED);
}
public void call(View view) {
if (checkPermission("android.permission.CALL_PHONE")) {
Intent call = new Intent(Intent.ACTION_DIAL);
String number = "tel:" + getString(R.string.phone_number);
call.setData(Uri.parse(number));
startActivity(call);
}
}
}
activity_report.xml
android:gravity="start"
android:hint="#string/Hint"
android:inputType="text"
android:textAlignment="textStart"
android:textCursorDrawable="#drawable/color_cursor"
app:layout_constraintBottom_toTopOf="#+id/submit_btn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/submit_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="80dp"
android:layout_marginLeft="80dp"
android:layout_marginTop="32dp"
android:background="#drawable/yes_button"
android:text="Submit"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Incident_Report" />
<Button
android:id="#+id/back_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginEnd="80dp"
android:layout_marginRight="80dp"
android:background="#drawable/diagnose_button"
android:onClick="onClick"
android:text="Back"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Incident_Report" />
<Button
android:id="#+id/emergency_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="131dp"
android:layout_marginBottom="106dp"
android:background="#drawable/no_button"
android:onClick="call"
android:text="EMERGENCY"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/submit_btn" />
</androidx.constraintlayout.widget.ConstraintLayout>
If you plan on using android:onClick="call"in your xml then you should also have a corresponding function called callin your activity and the logic to perform the click goes inside it.
If you plan on extending the View.onClickListener then inside your override void onClick() you can have a switch statement of your button ids and perform your logic
alternatively you can ignore the first two and get the id of the button and implement the click logic inside the onCreate()

Setting background color of a button changes the size of button

I am creating an Alert Dialog on clicking an imageView .Code is given below:
imgEditStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this);
inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.dialog_edit_status, null);
builder.setView(dialogView);
dialog = builder.create();
dialog.show();
final EditText edtStatus = (EditText) dialogView.findViewById(R.id.editStatus);
Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
// btnOK.getBackground().setColorFilter(getResources().getColor(R.color.orange_color)), PorterDuff.Mode.SRC_ATOP);
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(getApplicationContext(), "OK clicked", Toast.LENGTH_SHORT).show();
String statusText = edtStatus.getText().toString().trim();
new UpdateStatusTask().execute(statusText);
}
});
Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Cancel clicked", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}
});
dialog_edit_status.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/editStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/margin20"
android:hint="Enter your status here"
android:paddingBottom="#dimen/padding10"
android:padding="#dimen/padding10"
android:textColor="#color/black_color"
android:textColorHint="#color/gray_color"
android:layout_marginBottom="#dimen/margin10"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/margin10">
<Button
android:id="#+id/btnOK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="#dimen/margin50"
android:text="OK"
android:background="#color/orange_color"
android:textColor="#color/white_color"/>
<Button
android:id="#+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="#dimen/margin50"
android:text="Cancel"
android:textColor="#color/white_color"/>
</RelativeLayout>
</LinearLayout>
I am trying to set orange color in the background of OK button.But its size got changed. I tried to use the following code :
btnOK.getBackground().setColorFilter(getResources().getColor(R.color.orange_color)), PorterDuff.Mode.SRC_ATOP);
it is giving me error :setColorFilter() in Drawable can not be applied to (int) . Please help me to fix the issue
If you want to change the background color but retain other styles, then below might help.
btnOK.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.MULTIPLY);
try this:
btnOK.setBackgroundColor(getResources().getColor(R.color.orange_color));
btnOK.setBackgroundResource(R.color.orange_color);

Android custom dialog dismiss() redraws the box

I have accept and reject button, both to dismiss the dialog box. I also have a condition where the dialog will be removed if there is no action by the user, but it is redrawn after being removed. Upon thorough investigation I found out the dialog box was redrawn right after it is removed. This is my code:
LayoutInflater inflater = getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.dialog_layout, null);
builder.setView(dialoglayout);
builder.setTitle("REQUEST");
builder.setMessage("Would you like to accept?");
//builder.show();
dia = builder.create();
dia.show();
spRequest.play(spSoundId, 1, 1, 1, 15, 1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
dia.dismiss();
}
}, 7000); //the alert will play for 7 seconds and stop
//dia.show();
Button accept = (Button) dialoglayout.findViewById(R.id.bAcceptRequest);
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//mDialog.cancel();
dia.dismiss();
spRequest.release();
}
});
Button reject = (Button) dialoglayout.findViewById(R.id.bDeclineRequest);
reject.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//mDialog.cancel();
Log.e("caution", "dismiss reached");
dia.dismiss();
spRequest.release();
}
});
And this is my custom dialog xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dialog_layout_root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="#drawable/custom_dialog_background">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/bAcceptRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/acceptrequest"
android:background="#drawable/blue_button"
/>
<Button
android:id="#+id/bDeclineRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/rejectrequest"
android:background="#drawable/blue_button"
/>
</LinearLayout>
Can someone explain to why the dialog is being redrawn and how to stop that behavior?

What is the best way of creating a reusable dialog with Activity's lifecycle?

I'd like to build..
A reusable dialog
Fully customizable layout (custom color or typeface, etc)
Maintain its lifecycle with referenced Activity
Use overloading which I can create several variations of dialog, i.e. combination of title, message and callbacks
In a simple way (if possible)
Currently my custom dialog class looks like :
public class CustomAlert {
public interface OnSingleClickedListener {
public void onPositiveClicked();
}
public interface OnDualClickedListener {
public void onPositiveClicked();
public void onNegativeClicked();
}
/**
* Show simple alert without callback.
* #param context
* #param msg
*/
public static void showAlert(Context context, String msg) {
final Dialog dialog = new Dialog(context);
// Do some stuff
ok.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
/**
* Show simple alert with callback.
* #param context
* #param msg
* #param listener
*/
public static void showAlert(Context context, String msg, final OnSingleClickedListener listener) {
final Dialog dialog = new Dialog(context);
// Do some stuff
ok.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
listener.onPositiveClicked();
}
});
dialog.show();
}
// Some other methods..
}
and I call these alerts from Activity like this :
if(!isFinishing()) {
CustomAlert.showAlert(MainActivity.this, getResources().getString(R.string.network_no_connection));
}
Even though I'm calling isFinishing() to check if the host Activity is running, I keep seeing BadTokenException, is your Activity running?, and I thought maybe isFinishing() is not enough.
I found this article which is using DialogFragment, but I feel like this is quite a lot of code for such a small task when I consider above requirements.
What is the most recommended and effective solution to solve this problem?
Thanks in advance!
Create a custom class like this,i have created this dialog for thumbs up and thumbs down in my application named Debongo - Restaurant Finder on play store
//recommend dialog
public void showRecommendDialog(Context mContext)
{
dialog = new Dialog(mContext,android.R.style.Theme_Holo_Dialog_NoActionBar);
dialog.setContentView(R.layout.recommend_dialog);
dialog.show();
btnThumbsUp = (ImageButton) dialog.findViewById(R.id.btn_Yes);
btnThumbsDown = (ImageButton) dialog.findViewById(R.id.btn_no);
txtMsg=(TextView) dialog.findViewById(R.id.txtMsg);
ImageButton cancelRecommend=(ImageButton) dialog.findViewById(R.id.cancelRecommend);
cancelRecommend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
dialog=null;
}
});
btnThumbsUp.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//do what you want
}
});
btnThumbsDown.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//do what you want
}
});
}
Here is the layout file for the same
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:gravity="center"
android:padding="5dp" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<ImageButton
android:id="#+id/cancelRecommend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#android:color/transparent"
android:contentDescription="#null"
android:src="#drawable/com_facebook_close" />
<TextView
android:id="#+id/txtMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/cancelRecommend"
android:layout_marginBottom="#dimen/viewSpace3"
android:layout_marginLeft="#dimen/viewSpace3"
android:layout_marginRight="#dimen/viewSpace3"
android:text="Do You Want To Recommend This Restaurant ?"
android:textColor="#000000"
android:textSize="#dimen/titlebar_textSize"
tools:ignore="HardcodedText" />
<View
android:layout_width="0dip"
android:layout_height="#dimen/viewSpace3" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/txtMsg"
android:layout_centerHorizontal="true"
android:layout_gravity="center" >
<ImageButton
android:id="#+id/btn_Yes"
android:layout_width="#dimen/viewSpace5"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:contentDescription="#null"
android:src="#drawable/unselected_thumbs_up" />
<View
android:id="#+id/vvv"
android:layout_width="#dimen/viewSpace1"
android:layout_height="#dimen/viewSpace3"
android:layout_toRightOf="#id/btn_Yes" />
<ImageButton
android:id="#+id/btn_no"
android:layout_width="#dimen/viewSpace5"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/vvv"
android:background="#android:color/transparent"
android:contentDescription="#null"
android:src="#drawable/unselected_thumbs_down" />
</RelativeLayout>
</RelativeLayout>
Now when you want to open this dialog,you can just call it by using
showRecommendDialog(this);

How to keep an alertdialog open after button onclick is fired? [duplicate]

This question already has answers here:
How to prevent a dialog from closing when a button is clicked
(21 answers)
Closed 3 years ago.
The subject kinda says it all.. I'm requesting a PIN code from the user, if they enter it, click the OK Positive Button and the PIN is incorrect I want to display a Toast but keep the dialog open. At the moment it closes automatically.. Sure this is very trivial thing to correct but can't find the answer yet.
Thanks..
You do not need to create a custom class. You can register a View.OnClickListener for the AlertDialog. This listener will not dismiss the AlertDialog. The trick here is that you need to register the listener after the dialog has been shown, but it can neatly be done inside an OnShowListener. You can use an accessory boolean variable to check if this has already been done so that it will only be done once:
/*
* Prepare the alert with a Builder.
*/
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setNegativeButton("Button", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
});
this.alert = b.create();
/*
* Add an OnShowListener to change the OnClickListener on the
* first time the alert is shown. Calling getButton() before
* the alert is shown will return null. Then use a regular
* View.OnClickListener for the button, which will not
* dismiss the AlertDialog after it has been called.
*/
this.alertReady = false;
alert.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
if (alertReady == false) {
Button button = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
alertReady = true;
}
}
});
Part of this solution was provided by http://groups.google.com/group/android-developers/browse_thread/thread/fb56c8721b850124#
Build a custom dialog with a EditText with the attribute android:password="true" a button, then manually set onClick listener the button, and explicitly choose what to do in it.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minWidth="180dip"
android:digits="1234567890"
android:maxLength="4"
android:password="true"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/Accept"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Accept"/>
</LinearLayout>
</LinearLayout>
Then when you want it to pop up:
final Dialog dialog = new Dialog(RealizarPago.this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("PIN number:");
dialog.setCancelable(true);
Button button = (Button) dialog.findViewById(R.id.Accept);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(password_wrong){
// showToast
} else{
dialog.dismiss();
// other stuff to do
}
}
});
dialog.show();
You can set an OnClickListener as follows to keep the dialog open:
public class MyDialog extends AlertDialog {
public MyDialog(Context context) {
super(context);
setMessage("Hello");
setButton(AlertDialog.BUTTON_POSITIVE, "Ok", (new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// this will never be called
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ok) {
// do something
dismiss();
} else {
Toast.makeText(getContext(), "when you see this message, the dialog should stay open", Toast.LENGTH_SHORT).show();
}
}
});
}
}
You can just continue using the dialog you already have, just put an if clause in the onClick() saying
if(pin_check_method){ //pin_check_method should be a boolean returned method
//close the Dialog, then continue
}
else{
//dont put the dialog.dismiss() in here, put instead
Toast.makeText(getApplicationContext(),"Invalid pin, please try again",Toast.LENGTH_LONG).show();
}
Now, to use this code, simply invoke text.setText(""); and put in the text you want here
common error is that when you type in:
TextView text = (TextView) findViewById(R.id.dialog);
you miss that it needs to actually be
dialog.findViewById
and this is regardless of what the name of the dialog is, in my example it just happens to be the same name.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="#+id/text"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"/>
<Button android:text="Continue"
android:id="#+id/Button01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_below="#+id/text">
</Button>
</RelativeLayout>
Try this:
final AlertDialog alertDialog = new AlertDialog.Builder(context)
.setView(v)
.setTitle(R.string.my_title)
.setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
.setNegativeButton(android.R.string.cancel, null)
.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Do something
}
});
}
});
alertDialog.show();
Source: Prevent Alertdialog from closing after button click
Hope This Helps! Good Luck!
Same problem for me in a FragmentDialog. Here's my criminal/elegant solution:
Remove all buttons from the dialog (positive,negative,neutral). Add your buttons from the xml.eg.:
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:id="#+id/button_cancel"
style="#style/Widget.AppCompat.Button.Borderless.Colored"
android:text="#android:string/cancel"
android:layout_gravity="left"
/>
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:id="#+id/button_ok"
style="#style/Widget.AppCompat.Button.Borderless.Colored"
android:text="#android:string/ok"
android:layout_gravity="right"
/>
</LinearLayout>
And then in your code handle it with:
view.findViewById(R.id.button_ok).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view2) {
if (wannaClose)
dismiss();
else
//do stuff without closing!
}
});
where view is the view assigned to the dialog!

Categories

Resources