Как отобразить алертиалдиалог поверх других алертилдиалогов? И когда один на переднем плане закрыт, то на заднем плане должен быть виден - PullRequest
0 голосов
/ 29 сентября 2011

Это мой код для редактирования / обновления, который я выполняю с помощью настраиваемого модуля alerttdialog, содержащего данные, полученные из базы данных.Теперь, когда введенные данные являются неправильными, я хочу показать другие alerttdialog поверх этого, предоставляя некоторое сообщение пользователю.Когда пользователь отклоняет это сообщение alerttdialog, должно быть видно предыдущее сообщение, которое используется для обновления.Как я могу это сделать?

public class CountryEdit extends ListActivity{

    private Long mRowId;
    private CountryDbAdapter mDbHelper;
    public static final String PROVIDER_NAME = "assignment2.demos.MyCountriesCP";
    public static final String uriString = "content://"+ PROVIDER_NAME +"/countries";
    public static final Uri CONTENT_URI = Uri.parse(uriString);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ContentResolver contentResolver = getContentResolver();


        Cursor c = contentResolver.query(CONTENT_URI, null, null, null, getIntent().getExtras().getString("SORT_ORDER"));       
        String[] from = new String[] { "year", "country" };
        int[] to = new int[] { R.id.year, R.id.country };       
        SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.country_row,
                                        c, from, to);       
        setListAdapter(sca);

        mRowId = savedInstanceState != null ? savedInstanceState.getLong(assignment2.demos.MyCountriesActivity.KEY_ROWID) 
                : null;
        if (mRowId == null) {
            Bundle extras = getIntent().getExtras();            
            mRowId = extras != null ? extras.getLong(assignment2.demos.MyCountriesActivity.KEY_ROWID) 
                    : null;
        }

        populateFields();
    }



    private void populateFields() {

        LayoutInflater inflater=LayoutInflater.from(this);
        final View addView=inflater.inflate(R.layout.add_country, null);
        Cursor c = getContentResolver().query(CONTENT_URI.buildUpon().
                            appendPath(String.valueOf(mRowId)).build(), null, null, null, null);

        /* Read alert input */
        final EditText editCountry =(EditText)addView.findViewById(R.id.editCountry);
        final EditText editYear =(EditText)addView.findViewById(R.id.editYear);
            editCountry.setText(c.getString(c.getColumnIndex("country")));
            editYear.setText(c.getString(c.getColumnIndex("year")));

        new AlertDialog.Builder(this)
            .setTitle("Edit country/year")
            .setView(addView)
            .setPositiveButton("OK", 
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int whichButton) {

                            String country = editCountry.getText().toString();

                            if(country.trim().length()>0 && editYear.getText().toString().trim().length()>0){   
                                int year = Integer.parseInt(editYear.getText().toString());
                                ContentValues updateValues = new ContentValues();

                                updateValues.put(mDbHelper.COUNTRY, country);
                                updateValues.put(mDbHelper.YEAR, year);
                                getContentResolver().update(
                                            CONTENT_URI.buildUpon().appendPath(String.valueOf(mRowId)).build(), updateValues, null, null);
                                finish();
                            }
                            else{   
                                new AlertDialog.Builder(CountryEdit.this)
                                    .setTitle("Invalid Inputs!")
                                    .setMessage("You need to enter Country AND Year.")
                                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        // here you can add functions
                                        finish();
                                     }
                                  }).show();


//                              Toast.makeText(CountryEdit.this,
//                                      "You need to enter Country AND Year.", Toast.LENGTH_LONG).show();
                                //finish();
                            }
                        }
                    })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int whichButton) {
                            // ignore, just dismiss
                            finish();
                        }
                    })
            .show();
    }

}

1 Ответ

0 голосов
/ 29 сентября 2011

Первое диалоговое окно оповещения закрывается, когда появляется второе (когда заканчивается прослушивание щелчков). Вы не можете избежать этого.

Есть грязный хак, где вы можете переопределить прослушиватель щелчков, созданный строителем следующим образом:

create().getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener( ... }

Но я не рекомендую делать это, если вы не знаете, что делаете (это может сломать Интернет; -).
Вы должны были бы закрыть диалог самостоятельно. Если вы этого не сделаете, он никогда не закроется, пользователь увидит его навсегда, и ему придется убить ваше приложение, чтобы запустить его снова.

...