Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get reference on TextView from XML layout in AlertDialog?

I have a curious problem with getting reference on TextView, SeekBar and other widgets. My AlertDialog looks like this:

public class LineDialog extends AlertDialog {
private static SeekBar seekBar1, seekBar2, seekBar3;
private static TextView textView1, textview2, textView3;

protected LineDialog(final Context context, final DrawView drawView) {
    super(context);

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View dialogLayout = inflater.inflate(R.layout.line_dialog, null);

    setView(dialogLayout);
    setTitle("Line properties");
    textView1 = (TextView) findViewById(R.id.textView1); // TODO Code crash here :(
    setButton("Ok", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            seekBar1 = (SeekBar) findViewById(R.id.seek1);
            // some other code...
        }
    });
}

When I want get reference in Line where is

textView1 = (TextView) findViewById(R.id.textView1);

Logcat send me an Error

requestFeature() must be called before adding content

But when I get reference in onClick() method in LineDiealog(AlertDialog) everything works fine. Unfortunately this is too late, because I need this reference before LineDialog.show() is called...

like image 381
west44 Avatar asked Oct 19 '25 05:10

west44


1 Answers

You almost had it there in your original code. You saved the View returned by LayoutInflater, so that's the one you should use when calling findViewById() so it must be dialogLayout.findViewById(...). I was having the same issue myself and works like charm now.

like image 159
M_Mendoza Avatar answered Oct 22 '25 07:10

M_Mendoza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!