Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set textview in custom dialog

Tags:

android

dialog

I have created a custom dialog but I cannot set a text into the textview that is in the dialog layout from java and my program crashes. what is my mistake?

public class Total_CBC extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.total_cbc);
    final TextView RBC_T = (TextView) findViewById(R.id.total_cbc_text_rbc);

    Button RBC_B = (Button) findViewById(R.id.total_cbc_btn_rbc);

    //

    RBC_B.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            showCustomDialog(RBC_T);
        }
    });
}


protected void showCustomDialog(final TextView _RBC_T) {
    final Dialog dialog = new Dialog(Total_CBC.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.dialog_edit);
    final EditText editText = (EditText) dialog.findViewById(R.id.dialog_edit_edittext);
    Button button = (Button) dialog.findViewById(R.id.dialog_edit_btn);
    TextView titel = (TextView) findViewById(R.id.dialog_edit_text_title);
    titel.setText("RBC");
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            _RBC_T.setText(editText.getText().toString());
            dialog.dismiss();
        }
    });
    dialog.show();
}

} when I deleat this line program work but i need to set text

titel.setText("RBC");
like image 283
Aminika Avatar asked Oct 13 '13 21:10

Aminika


2 Answers

change

 TextView titel = (TextView) findViewById(R.id.dialog_edit_text_title);

to

 TextView titel = (TextView) dialog.findViewById(R.id.dialog_edit_text_title);
like image 168
ilovepjs Avatar answered Sep 20 '22 12:09

ilovepjs


You are trying to set the text of the TextView before the dialog is shown and thats why it return null. The correct way is to set the text after the dialog is created:

Put this into your custom dialog

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        TextView titel = (TextView)dialog.findViewById(R.id.dialog_edit_text_title);
        titel.setText("RBC");
        return builder.create();
    }
like image 34
Jan Ziesse Avatar answered Sep 21 '22 12:09

Jan Ziesse