从AlertDialog更改按钮文本

时间:2012-12-30 14:18:57

标签: android android-layout dialog alert android-alertdialog

我是开发Android应用程序的新手,我想创建一个简单的Conterter应用程序,只是为了开始。在我看来,我有一个edittext和一个Button。如果我单击该按钮,它将打开一个带有字符串列表的AlertDialog。我无法弄清楚如何管理这个:当我点击AlertView中的一个项目时,我想将按钮的文本设置为选定的字符串并关闭AlertDialog。有人可以帮帮我吗?

public class VypocetDlzkyActivity extends Activity {

EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;

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




}

public void zmenPrevodZ(View view){

    final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
    AlertDialog.Builder builder = new AlertDialog.Builder(VypocetDlzkyActivity.this);
    builder.setTitle("Vyberte jednotku");
    builder.setItems(jednotkyDlzky,null);
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
        String value = jednotkyDlzky[item].toString();
        prevodDlzkaZtlacidlo.setText(value);
                 dialog.cancel();
    }
    };

    final AlertDialog alert = builder.create();
    alert.show();

}

2 个答案:

答案 0 :(得分:1)

您需要在onCreate()方法中设置这两个成员变量的值,如下所示:

HodnotaDlzka = (EditText)findViewById(R.id.xxxx);
prevodDlzkaZtlacidlo = (Button)findViewById(R.id.yyyy);

xxxx是您在activity_vypocet_dlzky.xml中为EditText提供的ID,而yyyy是您为Button提供的ID。

此外,在AlertDialog中点击按钮后,对话框会自动关闭,因此您无需拨打dialog.cancel()

答案 1 :(得分:0)

问题是你没有添加onClick监听器。点击按钮你需要调用所需的方法。

public class MainActivity extends Activity implements OnClickListener {

EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    HodnotaDlzka = (EditText) findViewById(R.id.e1);
    prevodDlzkaZtlacidlo = (Button) findViewById(R.id.b1);
    prevodDlzkaZtlacidlo.setOnClickListener(this);

}


@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
     final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Vyberte jednotku");
        builder.setItems(jednotkyDlzky,new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
            String value = jednotkyDlzky[item].toString();
            prevodDlzkaZtlacidlo.setText(value);
        }
        });
    enter code here
        final AlertDialog alert = builder.create();
        alert.show();
}
}