0

我是为 android 开发应用程序的新手,我想创建一个简单的 Conterter 应用程序,只是为了开始。在我看来,我有一个编辑文本和一个按钮。如果我单击该按钮,它将打开一个带有字符串列表的 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();

}
4

2 回答 2

1

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

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

xxxx是您EditText在 activity_vypocet_dlzky.xml中提供yyyy的 ID,并且是您提供给Button.

此外,单击 中的按钮后AlertDialog,对话框会自动关闭,因此您无需调用dialog.cancel().

于 2012-12-30T14:25:54.323 回答
0

问题是您没有添加任何 onClick listnerz。单击按钮时,您需要调用所需的方法。

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();
}
}
于 2013-01-21T11:48:23.653 回答