4

EditText フィールドにテキストがない場合に [OK] ボタンを無効にする EditTextPreference が必要です。カスタム EditTextPreference クラスを作成し、EditText オブジェクトを取得して TextWatcher を設定できましたが、ボタンを無効にする方法が見つかりません。ダイアログの [OK] ボタンと [キャンセル] ボタンにアクセスできないようです。

これらのボタンにアクセスする方法、または私がやろうとしていることを行う方法を知っている人はいますか?

他の唯一のオプションは、EditTextPreference のように見え、それを模倣するカスタム ダイアログを最初から作成しようとすることです。

4

2 に答える 2

9

onCheckValue関数が を返すtrueかを返すかによってボタンを有効/無効にするコード サンプルを次に示しますfalse

public class ValidatedEditTextPreference extends EditTextPreference
{
    public ValidatedEditTextPreference(Context ctx, AttributeSet attrs, int defStyle)
    {
        super(ctx, attrs, defStyle);        
    }

    public ValidatedEditTextPreference(Context ctx, AttributeSet attrs)
    {
        super(ctx, attrs);                
    }

    private class EditTextWatcher implements TextWatcher
    {    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count){}

        @Override
        public void beforeTextChanged(CharSequence s, int start, int before, int count){}

        @Override
        public void afterTextChanged(Editable s)
        {        
            onEditTextChanged();
        }
    }
    EditTextWatcher m_watcher = new EditTextWatcher();

    /**
     * Return true in order to enable positive button or false to disable it.
     */
    protected boolean onCheckValue(String value)
    {        
        return Strings.hasValue(value);
    }

    protected void onEditTextChanged()
    {
        boolean enable = onCheckValue(getEditText().getText().toString());
        Dialog dlg = getDialog();
        if(dlg instanceof AlertDialog)
        {
            AlertDialog alertDlg = (AlertDialog)dlg;
            Button btn = alertDlg.getButton(AlertDialog.BUTTON_POSITIVE);
            btn.setEnabled(enable);                
        }
    }

    @Override
    protected void showDialog(Bundle state)
    {
        super.showDialog(state);

        getEditText().removeTextChangedListener(m_watcher);
        getEditText().addTextChangedListener(m_watcher);
        onEditTextChanged();
    }    
}
于 2011-01-21T19:34:50.530 に答える