How to use setText() to edit text in custom layout

2020-05-02 10:38发布

问题:

I have a TextView in a custom layout for dialog. Its text has to be changed when the dialog is about to appear.

      <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/final_score"
        />

java code I used to set text and show dialog is

AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();
    builder.setView(inflater.inflate(R.layout.its_over, null));
    AlertDialog dialog = builder.create();
    dialog.show();
    TextView t = (TextView)findViewById(R.id.final_score);
    t.setText(""+score);

i have also tried this code.

 AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();
    builder.setView(inflater.inflate(R.layout.its_over, null));
    AlertDialog dialog = builder.create();
    TextView t = (TextView)dialog.findViewById(R.id.final_score);
    t.setText(""+score);
    dialog.show();

but the app would crash when these method is called.

but if we remove

TextView t = (TextView)dialog.findViewById(R.id.final_score);
    t.setText(""+score);

it does not crash.

回答1:

Try to access the TextView by it's parent referance

View view = inflater.inflate(R.layout.its_over, null);
builder.setView(view);
TextView t = (TextView) view.findViewById(R.id.final_score);