I'm trying to set the linktextcolor of the message in AlertDialog. But when I try to findViewById my app crashes. What am I doing wrong? Do I need to have message in the XML for the activity?
final AlertDialog d = new AlertDialog.Builder(new ContextThemeWrapper(SplashPage.this, R.style.Theme_Sherlock_Light_Dialog))
.setIcon(android.R.drawable.ic_dialog_info).setTitle(getString(R.string.termsTitle))
//.setView(message).setCancelable(false)
.setMessage(Html.fromHtml(getString(R.string.terms))).setCancelable(false)
.setPositiveButton(getString(R.string.accept), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
app.setTermsAccepted(true);
dialogInterface.dismiss();
Intent intent = new Intent(SplashPage.this, LoginPage.class);
startActivity(intent);
}
}).create();
//FAILING: TextView TV = (TextView)d.findViewById(android.R.id.message);
//TV.setLinkTextColor(Color.MAGENTA);
I looked at the AlertDialog documentation and it appears that when you call its method, it searches an XML that you've processed in its onStart method (http://developer.android.com/reference/android/app/Dialog.html#findViewById%28int%29). Instead, simply call your activity's findViewById method (e.g. if this is in an activity class, just calling:
TextView TV = (TextView) findViewById(android.R.id.message);
should work.)
If you are using a DialogFragment, it is accessible after DialogFragment.onStart() method as eluded to in the prior answer.
#Override
public void onStart() {
super.onStart();
final TextView textView = (TextView) getDialog().findViewById(android.R.id.message);
//Do something!
}
Related
I want to finish the activity when custom dialog is cancelled or dismissed. But when I use .setOnDismissListener in other classes, it is never being reached inside. I've found several problems, but the solution was to override onDismiss method inside the customDialog class. But I do not need to override onDismiss method for every customDialog I create. What should I do?
This is the code I call in another class, but never receive message in log "setOnDismissListener".
customDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
Log.d(TAG, "setOnDismissListener");
}
});
My CustomDialog class:
public class CustomDialog extends Dialog {
private static final String TAG = "CustomDialog";
public CustomDialog(Context context, String title, String message) {
super(context);
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setPadding(10, 50, 10, 10);
textView.setText(title);
textView.setTextColor(Color.BLACK);
textView.setTextSize(20);
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
textView.setTypeface(boldTypeface);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder
.setCustomTitle(textView)
.setMessage(message)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog customDialog = builder.show();
TextView messageText = customDialog.findViewById(android.R.id.message);
if (messageText != null) {
messageText.setGravity(Gravity.CENTER);
messageText.setTextColor(Color.GRAY);
} else {
Log.w(TAG, "messageText is null");
}
}
}
Yeah, so if you are not using some API to parse information, or are using local variables I suggest you do whatever functionality you want to do in your onClickListener() Method.
The problem is that you are using your CustomDialog which itself extends the Dialog Class. But instead of using that you create a new alert dialog and build that. You dismiss it, but the dialog which is dismissed is not your custom dialog class, but the builder dialog you created in your constructor. Even if you fixed for that, it introduces unnecessary complications.
What I suggest you do is create the Intent in your onClickListener() function. The way to do that would be to change your constructor to support a callback listener. Simply put you cannot just add an onDismissListener() when the dialog you listen to is another one. What you can do is pass in the function that you want to do when the user dismisses the dialog as a special case. See below.
So, first, modify your constructor like this:
public CustomDialog(Context context, String title, String message,
DialogInterface.OnClickListener listener) {
super(context);
}
In your constructor paste your previous code:
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setPadding(10, 50, 10, 10);
textView.setText(title);
textView.setTextColor(Color.BLACK);
textView.setTextSize(20);
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
textView.setTypeface(boldTypeface);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder
.setCustomTitle(textView)
.setMessage(message)
.setPositiveButton("Ok", listener);
AlertDialog customDialog = builder.show();
TextView messageText = customDialog.findViewById(android.R.id.message);
if (messageText != null) {
messageText.setGravity(Gravity.CENTER);
messageText.setTextColor(Color.GRAY);
} else {
Log.w(TAG, "messageText is null");
}
What you do is where you used to create a new onClickListener() you pass in the listener parameter.
Go to your MainActivity or where you create your custom dialog. There do this:
CustomDialog customDialog = new CustomDialog(FirstActivity.this, "Title", "Message",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do your functionality here.
Intent intent = new Intent(context, activity.class);
//Add any flags if you want
...
context.startActivity(intent);
//Or you can simply do context.finish();
}
});
When you don't want to pass a onClickListener()(meaning when you don't want to finish() the activity) pass in null.
It would work. If this is not what you wanted, tell me and I will fix it.
Make an interface like
interface OnUserInformedCallback {
fun positive()
fun negative()
}
and implement this in your activity and pass it to the dialog method from where you are gettingdialog and you will get callback of ok and cancle in you activity.
code is like that
fun alertDialog(
context: Context,
message: String,
positiveText: String,
isUa: Boolean,
callback: OnUserInformedCallback
): Dialog {
val dialog = Dialog(context, android.R.style.Theme_Translucent_NoTitleBar)
dialog.setContentView(R.layout.alert_dialog_layout)
dialog.window?.setGravity(Gravity.CENTER)
dialog.setCancelable(true)
dialog.setCanceledOnTouchOutside(true)
val tvOk: TextView = dialog.findViewById(R.id.visit)
val tvMsg: TextView = dialog.findViewById(R.id.mess)
tvMsg.text = message
tvOk.text = positiveText
dialog.findViewById<TextView>(R.id.cancel).setOnClickListener {
callback.negative()
}
tvOk.setOnClickListener {
callback.positive()
}
dialog.create()
return dialog
}
in java for default dialog
private AlertDialog getDialog(Activity context, String message, OnUserInformedCallback callbac) {
return new AlertDialog.Builder(context)
.setTitle(R.string.app_name).setMessage(message)
.setCancelable(true)
.setPositiveButton(android.R.string.yes, (dialog12, which) -> callbac.positive())
.setNegativeButton(android.R.string.yes, (dialog1, which) -> callbac.positive())
.create();
}
I am new to android development, I have got an weather app, My WeatherFragment class got below code, which is of a fragment class.
btn=(Button)rootView.findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Change city");
final EditText input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MainActivity obj=new MainActivity();
obj.changeCityLocation(input.getText().toString());
}
});
builder.show();
}
});
return rootView;
}
and I need to call changeCityLocation() which is in MainActivity, which code is:
public void changeCityLocation(String city){
WeatherFragment wf = (WeatherFragment)getSupportFragmentManager()
.findFragmentById(R.id.container);
wf.changeCity(city);
new CityPreference(this).setCity(city);
}
I need to take the input and store in city variable when I click ok but it crashed. Thank you all in advance.
You are doing wrong here
MainActivity obj=new MainActivity();
Because this is not possible. All Activities in android must go through the Activity lifecycle so that they have a valid context attached to activity. so you have to use getActivity() method to get parent activity object and then cast it to MainActivity. like this
((MainActivity) getActivity()).changeCityLocation(input.getText().toString());
This will allow you to access Parent activity methods from fragment.
I want to create a function for dialog method and reuse the function later on.
Code to create a dialog within a function:
private void alertView( String message ) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle( "Hello" )
.setIcon(R.drawable.ic_launcher)
.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i){
}
}).show();
}
Code to call this function:
alertView("My message");
This works fine but I want to center my message. I have looked for solutions and used various methods such as:
AlertDialog alert = dialog.show();
TextView messageText =(TextView)alert.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
messageText.setTextColor(Color.RED)
Nothing works. Could someone please help me with this?
Found a solution to my question from this website: http://examples.javacodegeeks.com/android/core/ui/dialog/android-custom-dialog-example/
Created an xml layout as described on the website and made a little change to the code in my java class:
private void alertView( String message ) {
//create a dialog component
final Dialog dialog = new Dialog(this);
//tell the dialog to use the dialog.xml as its layout description
dialog.setContentView(R.layout.dialog);
dialog.setTitle("your title");
TextView txt = (TextView) dialog.findViewById(R.id.txt);
txt.setText(message);
Button dialogButton = (Button)dialog.findViewById(R.id.dialogButton);
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mUartCom.write("D"); //change this
}
});
dialog.show();
}
and then I've reused this function numerous times by changing the message:
alertView("Please select one of the red icons to begin");
I have an AlertDialog that opens pressing a Button.
In this AlertDialog there are a button and a TextView showing a number.
I have to create a function that increments by 1 the number in the TextView when the button in the AlertDialog is pressed.
In order to do that, I wrote this into the .java file of the activity that opens the AlertDialog.
public void plus(View view)
{
TextView total = (TextView) findViewById(R.id.Total);
totalP = Integer.parseInt((String)(total.getText())) + 1;
total.setText(String.valueOf(totalP));
}
But it gives error on total.getText()
I tried to write something similar, but with the TextView into the activity, and it works fine.
I started programming Android a week ago, I'm not very good. Please, help me!
Thank you!
If your dialog variable is named diag, then try the following
TextView total = (TextView) diag.findViewById(R.id.Total);
Notice that you are calling the findViewById() on the Dialog not the Activity
final EditText input = new EditText(MainActivity.this);
input.setSingleLine(true);
new AlertDialog.Builder(MainActivity.this)
.setTitle("Title")
.setView(input)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String in = input.getText().toString();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.show();
In my app I am using AlertDialog with EditText. I want to move this code to method because it called few times. I try to implement it by this way:
private EditText showEditAlert(DialogInterface.OnClickListener listener) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(R.string.waypoint);
alert.setMessage(R.string.waypoint_alert_text);
EditText editText = new EditText(this);
alert.setView(editText);
alert.setPositiveButton(android.R.string.ok, listener);
alert.setNegativeButton(android.R.string.cancel, null);
alert.show();
return editText;
}
And then I want to use it:
final EditText editText = showEditAlert(new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Here is I am working with editText
// and here is I get error "The local variable editText may not have been initialized"
}
});
But I get "The local variable editText may not have been initialized" error. As I understand compiler think that the onClick() method will called before showEditAlert() returns value.
How to implement this correctly? Or may be I can just suppress this error?
Looks like the IDE's warning is precisely for the reason you suppose. I guess you could circumvent this by defining a custom interface for the listener (and it would probably be more clear to use, to boot). Something like:
interface EditAlertOkListener
{
void onEditAlertOk(EditText editText);
}
private void showEditAlert(final EditAlertOkListener listener)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
...
final EditText editText = new EditText(this);
alert.setView(editText);
alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
if (listener != null)
listener.onEditAlertOk(editText);
}
});
alert.setNegativeButton(android.R.string.cancel, null);
alert.show();
}
And then just call it with:
showEditAlert(new EditAlertOkListener() {
#Override
public void onEditAlertOk(EditText editText) {
// Use editText here.
}
});
PS. You can also have the method return the EditText, if needed, I just removed it to make this example clearer. Or also, if you just need the EditText contents, have the interface pass a CharSequence or String instead of the EditText itself. This is just a template. :)
Because the editText variable may not be initialized. The IDE could not check it when it is creating.
The solution here is use the keyword: "this"
final EditText editText = showEditAlert(new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
this.getText();// this mean editText, not its parent, if you want to use parent, you must have ParentClass.this
}
});