[Android] 设置AlertDialog中按钮的可用(Enable)状态

弹出一个保存文件的对话框,要控制输入内容限制,同时内容为空时保存按钮不可用。

原文地址请保留http://www.cnblogs.com/rossoneri/p/4140184.html

直接上代码:

LayoutInflater mInflater = LayoutInflater.from(mActivity);
View saveView = mInflater.inflate(R.layout.alert_dlg_save, null);
// 设置输入文件名的EditText属性
final EditText filename = (EditText) saveView.findViewById(R.id.dlg_save_input_filename);
filename.setFilters(new InputFilter[] {new InputFilter.LengthFilter(255), new SpecialFilter() });
filename.setText(mStrAsName);

TextView defaultPath = (TextView) saveView.findViewById(R.id.dlg_save_default_path);
defaultPath.setText(DataStruct.gFloder + "/");

AlertDialog.Builder builder = new AlertDialog.Builder(mActivity, AlertDialog.THEME_HOLO_LIGHT);
builder.setTitle(R.string.maker_menu_save);
builder.setIcon(R.drawable.icon_small);
builder.setView(saveView);
builder.setPositiveButton(R.string.maker_menu_save,
    new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog,int which) {
        // TODO Auto-generated method stub
        String name = filename.getText().toString().trim();

        name += ".astp";
        String namePath = DataStruct.gFloder + "/" + name;
        if (saveFile(namePath)) {
            mStrSavedPath = namePath;
            mBtnSave.setEnabled(false);
        } else {
            ToastFailedSave();
        }
    }
});
builder.setNegativeButton(R.string.btn_cancel,
    new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog,int which) {
        // TODO Auto-generated method stub

        }
    });

Dialog dialog = builder.create();
dialog.show();  //show()放在 监听文字改变事件之后会报错
// 获取PositiveButton 重点在这里
final Button btn = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE);
// 输入不能为空
filename.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start,int before, int count) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start,int count, int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        String name = s.toString().trim();
        if (name.isEmpty())
            btn.setEnabled(false);
        else
            btn.setEnabled(true);
    }
});

 

posted @ 2014-12-03 15:17  Wossoneri  阅读(5326)  评论(0编辑  收藏  举报