为什么我不显示positiveButton

时间:2015-04-22 15:31:55

标签: java android android-alertdialog

我使用“正面按钮”创建了AlertDialog,但在模拟器中它没有显示。有什么问题?

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnDersEkle = (Button) findViewById(R.id.btnDersEkle);
        etDers = new EditText(MainActivity.this);
        LayoutDers = (LinearLayout) findViewById(R.id.layoutDers);
        AlertDialog.Builder alertDers = new AlertDialog.Builder(MainActivity.this);
        alertDers.setTitle("Ders Adi Giriniz");
        alertDers.setView(etDers);
        final AlertDialog alert = alertDers.create();

        alertDers.setPositiveButton("TAMAM", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                tvDers = new TextView(MainActivity.this);
                tvDers.setText(etDers.getText().toString());
                LayoutDers.addView(tvDers);

            }
        });


        btnDersEkle.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.show();
            }
        });


    }
}

3 个答案:

答案 0 :(得分:1)

在创建setPositiveButton之前,您需要AlertDialog。试试这个:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnDersEkle = (Button) findViewById(R.id.btnDersEkle);
        etDers = new EditText(MainActivity.this);
        LayoutDers = (LinearLayout) findViewById(R.id.layoutDers);
        AlertDialog.Builder alertDers = new AlertDialog.Builder(MainActivity.this);
        alertDers.setTitle("Ders Adi Giriniz");
        alertDers.setView(etDers);
        alertDers.setPositiveButton("TAMAM", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                tvDers = new TextView(MainActivity.this);
                tvDers.setText(etDers.getText().toString());
                LayoutDers.addView(tvDers);

            }
        });
        final AlertDialog alert = alertDers.create();

        btnDersEkle.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.show();
            }
        });
    }
}

答案 1 :(得分:1)

创建AlertDialog后,您无法修改此类内容。

setPositiveButton()之前使用create()和其他方法

final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
.setPositiveButton(/* ... */)
.create();

答案 2 :(得分:0)

因为你也必须设置负片按钮。

alertDers.setNegativeButton("Button2", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
    //DO TASK
}

如果您不想显示此按钮,则可以执行以下操作:

alertDers.getButton(yourButton).setEnabled(false);