方法中的AlertDialog?

时间:2018-01-24 17:10:43

标签: android android-alertdialog

我想按下button1并将“one text”发送到一个textView并按下button2并将“另一个文本”发送到另一个textview。

我想使用相同的方法(displayAlert), 但我想我错过了什么。

或者这样不可能吗? Mabe有更好的方法。

这是我的代码:

public class LoggFactActivity extends AppCompatActivity{

final Context context = this;
private String hintText;
private TextView tv;
private TextView editTextview;

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logg_fact);


    //First button
    Button btn1 = (Button) findViewById(R.id.fact_btn_1);
    btn1.setOnClickListener(new View.OnClickListener() {
        final TextView loggTextView = (TextView)findViewById(R.id.text_1);
        @Override
        public void onClick(View view) {
            displayAlert("Reg.number", loggTextView);
        }
    });

    //Second button
    Button btn2 = (Button) findViewById(R.id.fact_btn_2);
    btn2.setOnClickListener(new View.OnClickListener() {
        final TextView loggTextView = (TextView)findViewById(R.id.text_2);
        @Override
        public void onClick(View view) {
            displayAlert("Modell", loggTextView);
        }
    });
}

public void displayAlert(String hintText, final TextView tv){

    //set the text in alertdialog text view
    editTextview = (EditText) findViewById(R.id.ad_logg_fact);
    editTextview.setHint(hintText);

    // get the logg_fact_alert_dialog view
    LayoutInflater li = LayoutInflater.from(context);
    View alertDialogView = li.inflate(R.layout.logg_fact_alert_dialog, null);

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

    // set logg_fact_alert_dialog to alertdialog builder
    alertDialogBuilder.setView(alertDialogView);

    final EditText userInput = alertDialogView.findViewById(R.id.ad_logg_fact);

    //set dialog message
    alertDialogBuilder.setCancelable(false).setPositiveButton("SAVE", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int i) {
            //get user input and set to result edit text
            tv.setText(userInput.getText());
        }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int i) {
            dialog.cancel();
        }
    });

    //create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();
    //Show it
    alertDialog.show();
}

}

1 个答案:

答案 0 :(得分:0)

你应该在膨胀对话框的内容视图后找到EditText并设置提示。

删除此行

//set the text in alertdialog text view
editTextview = (EditText) findViewById(R.id.ad_logg_fact);
editTextview.setHint(hintText);

添加此

userInput.setHint(hintText);

在线下

 final EditText userInput = alertDialogView.findViewById(R.id.ad_logg_fact);