java android getResources().getIdentifier() of elment at alertdialog with LayoutInflater - java

I try to get dynamically an identifier of some checkbox in a AlertDialog.
But I do not find the right code for this.
Every time I get return 0.
I have a test to get id of alert title ("android:id/alertTitle")
And this works fine. But I'am not able to reach my inflater-ID's
For me it seems like the context is wrong?
AlertDialog.Builder builder = new AlertDialog.Builder(Claim.this);
builder.setView(optionmenu);
final CheckBox[] myCheckBox = new CheckBox[checkedItems.length];
builder.setTitle("Select pages for claim");
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
for(int i=0; i<checkedItems.length; i++) {
String checkboxID = "android:id/optionspage"+i+"CheckBox";
int resID = builder.getContext().getResources().getIdentifier(checkboxID, null, null);
myCheckBox[i] = ((CheckBox) findViewById(resID));
myCheckBox[i].setChecked(checkedItems[i]);
}
What am I doing wrong here? Thanks.

Related

Is it possible to create two edit text in showAlert Dialog?

I just want to know if it is possible to create another edit text below my existing one and how to create it. The new one should also have a subtitle above the text line so users can differentiate which one is which. Thanks and have a great day.
private void showAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Cart.this);
alertDialog.setTitle("Requests:");
alertDialog.setMessage("(Condiments,napkins, take-out orders or such can also be requested here)");
final EditText edtAddress = new EditText(Cart.this);
final EditText edtRef = new EditText(Cart.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
edtAddress.setLayoutParams(lp);
alertDialog.setView(edtAddress);// Request Edit Txt
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Create new Request
Request request = new Request(
Common.currentTable.getTablet(),
edtAddress.getText().toString(),
txtTotalPrice.getText().toString(),
cart
);
// Submit to Firebase
requests.child(String.valueOf(System.currentTimeMillis()))
.setValue(request);
//Delete cart
new Database(getBaseContext()).cleanCart();
Toast.makeText(Cart.this, "Order Placed Thank You and Kindly Wait for your Order.", Toast.LENGTH_LONG).show();
finish();
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}

How to set checkbox checked and disabled

I have this code for showing list of languages for download:
public void onCreateDialog(ArrayList<String>fullLangArray, final ArrayList<String>codeLangArray) {
final String[] items = fullLangArray.toArray(new String[fullLangArray.size()]);
final ArrayList mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// Set the dialog title
builder.setTitle("Updates...")
.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected,
boolean isChecked) {
if (isChecked) {
mSelectedItems.add(Utils.SERVER_ADDRESS + "/" + codeLangArray.get(indexSelected) + ".zip");
} else if (mSelectedItems.contains(indexSelected)) {
mSelectedItems.remove(Integer.valueOf(indexSelected));
}
}
})
.setPositiveButton("Download", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
DownloadTask downloadTask = new DownloadTask(MainActivity.this);
downloadTask.execute(mSelectedItems.toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
I want to make a one item of a checkbox is checked and "disabled" like in a photo (Option 3) when AlertDialog is loaded.
Can you help me how to do it?
You can check the checkbox by using the setChecked() method which boolean value as parameter.
Example:
option1.setChecked(true);
and also uncheck it using
option2.setChecked(false);
If you want to set it to checked and disabled you have use setEnabled() which takes boolean as it's parameters.
Example.
option3.setChecked(true);
option3.setEnabled(false);
This will disable your checkbox and even check it. I hope this was helpful. ThankYou.
For setting Opacity
mSelectedItems.getBackground().setAlpha(128);
Where the INT ranges from 0 (fully transparent) to 255 (fully opaque).
For setChecked item
mSelectedItems.setChecked(true);
Disable checking
mSelectedItems.setEnabled(false)

AlertDialog Closing Automatically

I have an AlertDialog for showing a small form to the user.
On the ALertDialog are 2 buttons; namely "Submit" & "Cancel".
Now the fields (EditTexts) have setKeyListeners attached to them individually.
The problem which I face is suppose the user doesn't fills in any field and directly clicks on Submit button then the dialog box closes automatically.
Here's my Method which is called for creating/showing the Dialog Box:
Context ctx = this.getApplicationContext();
LinearLayout layoutCreateMerch = new LinearLayout(ctx);
layoutCreateMerch.setOrientation(LinearLayout.VERTICAL);
layoutCreateMerch.setVerticalScrollBarEnabled(true);
final AlertDialog.Builder alert = new AlertDialog.Builder(Store.this);
alert.setTitle("New Store");
final EditText stoName = new EditText(Store.this);
final EditText stoDesc = new EditText(Store.this);
InputFilter[] FilterMaxLen = new InputFilter[1];
FilterMaxLen[0] = new InputFilter.LengthFilter(25);
stoName.setFilters(FilterMaxLen);
stoName.setHint("Store's Name");
stoName.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,&apos;1234567890 "));
stoName.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
layoutCreateMerch.addView(stoName);
stoDesc.setFilters(FilterMaxLen);
stoDesc.setHint("Store's Description");
stoDesc.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,&apos;1234567890 "));
stoDesc.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
layoutCreateMerch.addView(stoDesc);
ScrollView scroll = new ScrollView(ctx);
scroll.setBackgroundColor(Color.TRANSPARENT);
scroll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
scroll.addView(layoutCreateMerch);
alert.setView(scroll);
alert.setNeutralButton("Submit",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (Name.getText().toString().equals("")
|| Desc.getText().toString().equals(""))
{
if(stoName.getText().toString().equals("")){
stoName.setHint("fill Store's Name");
stoName.setHintTextColor(Color.RED);
}
else{}
if( stoDesc.getText().toString().equals("")){
stoDesc.setHint("fill Store's Description");
stoDesc.setHintTextColor(Color.RED);
}
else{}
if..
..
..
}
else {
System.out.println("should not exit :| ");
}
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.cancel();
}
});
alert.show();
Any advice is appreciated..
Thanks
Add addTextChangedListener for your EditText and then always check user have entered any text or not as if not disable the submit button else enable the submit button dynamically.

Android Linkify text in dialog

Hi I've gone through all of the different linkify tutorials I could find but none of them work here is my current code:
final SpannableString s = new SpannableString("Please send any questions to email#fake.com");
Linkify.addLinks(s, Linkify.EMAIL_ADDRESSES);
AlertDialog.Builder builder = new AlertDialog.Builder(Activity.this);
builder.setTitle("Warning!")
.setMessage(s)
.setCancelable(false)
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Decline", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Activity.this.finish();
}
}).show();
However when I actually run the app it shows the text like blue and underlined as if it were linked but selecting the text doesn't prompt to open the email app. I've also tried with urls and the browser doesn't work is there something that's missing?
Thanks for any help.
In order to have a clickable area on dialog you need to use TextView (View) and set autoLink=all in layout file or invoke setAutoLinkMask() method from within the code.
final SpannableString s = new SpannableString("Please send any questions to email#fake.com");
//added a TextView
final TextView tx1=new TextView(this);
tx1.setText(s);
tx1.setAutoLinkMask(RESULT_OK);
tx1.setMovementMethod(LinkMovementMethod.getInstance());
Linkify.addLinks(s, Linkify.EMAIL_ADDRESSES);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Warning!")
.setCancelable(false)
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Decline", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setView(tx1)
.show();
Here's Kotlin in case it's helpful:
val s = SpannableString(getString(R.string.actions_list_info_button_body))
val tx1 = TextView(context!!)
tx1.text = s
tx1.autoLinkMask = RESULT_OK
tx1.movementMethod = LinkMovementMethod.getInstance()
The rest is the same.
The result likely will not look great so you probably will want to add some padding as well:
// Adjust Padding to dp
val scale: Float = resources.displayMetrics.density
val dpAsPixels: Int = (25 * scale + 0.5f).toInt()
text.setPadding(dpAsPixels,20,dpAsPixels,0)
Alternatively, you can reuse the TextView created.
AlertDialog.Builder builder;
builder.setMessage(R.string.yourMessage);
Dialog dialog = builder.create();
dialog.setOnShowListener(d -> {
TextView text = dialog.getWindow().findViewById(android.R.id.message);
text.setAutoLinkMask(Linkify.ALL);
text.setMovementMethod(LinkMovementMethod.getInstance());
});

Null Validation on EditText box in Alert Dialog - Android

I am trying to add some text validation to an edit text field located within an alert dialog box. It prompts a user to enter in a name.
I want to add some validation so that if what they have entered is blank or null, it does not do anything apart from creating a Toast saying error.
So far I have:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Record New Track");
alert.setMessage("Please Name Your Track:");
// Set an EditText view to get user input
final EditText trackName = new EditText(this);
alert.setView(trackName);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String textString = trackName.getText().toString(); // Converts the value of getText to a string.
if (textString != null && textString.trim().length() ==0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + textString;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
}
else
{
SQLiteDatabase db = waypoints.getWritableDatabase();
ContentValues trackvalues = new ContentValues();
trackvalues.put(TRACK_NAME, textString);
trackvalues.put(TRACK_START_TIME,tracktimeidentifier );
insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues);
}
But this just closes the Alert Dialog and then displays the Toast. I want the Alert Dialog to still be on the screen.
Thanks
I think you should recreate the Dialog, as it seems the DialogInterface given as a parameter in onClick() doesn't give you an option to stop the closure of the Dialog.
I also have a couple of tips for you:
Try using Activity.onCreateDialog(), Activity.onPrepareDialog() and of course Activity.showDialog(). They make dialog usage much easier (atleast for me), also dialog usage looks more like menu usage. Using these methods, you will also be able to more easilty show the dialog again.
I want to give you a tip. It's not an answer to your question, but doing this in an answer is much more readable.
Instead of holding a reference to an AlertDialog.Builder() object, you can simply do:
new AlertDialog.Builder(this)
.setTitle("Record New Track")
.setMessage("Please Name Your Track:")
//and some more method calls
.create();
//or .show();
Saves you a reference and a lot of typing ;). (almost?) All methods of AlertDialog.Builder return an AlertDialog.Builder object, which you can directly call a method on.
The same goes for Toasts:
Toast.makeText(this, "Please enter...", Toast.LENGTH_LONG).show();
I make a new method inside my class that shows the alert and put all the code for creating the alert in that one method. then after calling the Toast I call that method. Say I named that method createAlert(), then I have,
createAlert(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Record New Track");
alert.setMessage("Please Name Your Track:");
// Set an EditText view to get user input
final EditText trackName = new EditText(this);
alert.setView(trackName);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String textString = trackName.getText().toString(); // Converts the value of getText to a string.
if (textString != null && textString.trim().length() ==0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + textString;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
createAlert();
}
else
{
SQLiteDatabase db = waypoints.getWritableDatabase();
ContentValues trackvalues = new ContentValues();
trackvalues.put(TRACK_NAME, textString);
trackvalues.put(TRACK_START_TIME,tracktimeidentifier );
insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues);
}
}
What you should do is to create a custom xml layout including a textbox and an Ok button instead of using .setPositiveButton.
Then you can add a click listener to your button in order to validate the data and dismiss the dialog.
It should be used in CreateDialog:
protected Dialog onCreateDialog(int id)
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (id==EDIT_DIALOG)
{
final View layout = inflater.inflate(R.layout.edit_dialog, (ViewGroup) findViewById(R.id.Layout_Edit));
final Button okButton=(Button) layout.findViewById(R.id.Button_OkTrack);
final EditText name=(EditText) layout.findViewById(R.id.EditText_Name);
okButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
String textString = trackName.getText().toString();
if (textString != null && textString.trim().length() ==0)
{
Toast.makeText(getApplicationContext(), "Please enter...", Toast.LENGTH_LONG).show();
} else
removeDialog(DIALOG_EDITTRACK);
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setTitle("Edit text");
AlertDialog submitDialog = builder.create();
return submitDialog;
}
Even though it's an old post, the code below will help somebody. I used a customized layout and extended DialogFragment class.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the layout inflater
LayoutInflater inflater = requireActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.Name_of_the_customized_layout, null);
final EditText etxtChamp = view.findViewById(R.id.editText);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Enter a Name")
.setTitle("Mandatory field ex.");
builder.setView(view);
final Button btnOk = view.findViewById(R.id.ok);
final Button btnCancel = view.findViewById(R.id.cancel);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(etxtChamp.getText().toString().isEmpty()){
etxtChamp.setError("Oups! ce champ est obligatoire!");
}else{
//Get the editText content and do whatever you want
String messageEditText = etxtChamp.getText().toString();
dismiss();
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
return builder.create();
}
Use This code for displaying Dialog.
public void onClick(DialogInterface dialog, int whichButton) {
String textSt`enter code here`ring = trackName.getText().toString(); // Converts the value of getText to a string.
if (textString != null && textString.trim().length() ==0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + textString;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
new AlertDialog.Builder(this)
.setTitle("Message")
.setMessage("please enter valid field")
.setPositiveButton("OK", null).show();
}
This will create a Dialog for you, editText is empty or what are conditions you wants.
//if view is not instantiated,it always returns null for edittext values.
View v = inflater.inflate(R.layout.new_location_dialog, null);
builder.setView(v);
final EditText titleBox = (EditText)v.findViewById(R.id.title);
final EditText descriptionBox = (EditText)v.findViewById(R.id.description);

Categories

Resources