4

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...

west44
  • 747
  • 3
  • 12
  • 24

3 Answers3

4

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.

rayryeng
  • 102,964
  • 22
  • 184
  • 193
M_Mendoza
  • 41
  • 2
1

Here is an example of the custom AlertDialogbox and How to implement a custom AlertDialog View you can see how to add the view to the alertdialogbox.

Community
  • 1
  • 1
V.J.
  • 9,492
  • 4
  • 33
  • 49
  • Thanks for link, but its little different situation. They have Dialog like inner class and they can call ' TextView text = (TextView) dialog.findViewById(R.id.TextView01)'. In my case doesnt exist any dialog instance because its in her constructor.. – west44 May 08 '12 at 09:26
1

You must either reference your textView by LinearLayout or by android:id in the xml file.

LinearLayout example:

LinearLayout mainLinear = new LinearLayout(this);
mainLinear.addView(textBox);

the add text to the box:

textBox.addText("This is the text to add to the text box");

xml reference (you must create the text box in xml first!!!!):

TextView text1=(TextView) findViewById(R.id.NAME);
text1.setText("Hello please pick an option below");

The NAME portion must be replaced with the android:id name in the .xml file

Rilcon42
  • 9,584
  • 18
  • 83
  • 167