如何在自定义对话框中的edittext上添加侦听器

时间:2016-12-06 12:03:42

标签: android dialog android-edittext listener

我想实现一个对话框来接收密码输入并验证它。现在我已经定义了一个对话框类,oncreate函数将使用我自己的布局文件setContentView。

    MyDialog class {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.ms_pdf_viewer_password_layout);
    }
}

这是XML

<EditText
    android:imeOptions="actionGo"
    android:layout_marginLeft="4dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:textColorHint="@color/hint_text_color"
    android:textColor="@color/text_color"
    android:textSize="12dp"
    android:hint="Please enter the password"
    android:ems="10"
    android:id="@+id/editText"/>

我在片段中创建了一个对话框对象,我想处理按下输入按钮并验证输入密码,但是监听器不工作,actionID无法打印出来。我想也许我没有正确地获得editText对象。

 Dialog dialog = new PdfPasswordDialog(getActivity());
 View view = inflater.inflate(R.layout.ms_pdf_viewer_password_layout, container, false);
EditText editText = (EditText) dialog.findViewById(R.id.editText);



editText.setOnEditorActionListener(
            new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    Log.i(sClassTag,"actionID is "+actionId);

如何在自定义对话框中的edittext上添加侦听器来处理密码输入?任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:0)

如果您想在输入新字符时更改或操作文本或检查输入的文字,可以使用TextWatcher这里有一个例子:

TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {
                // when the change is done
            }
        };

答案 1 :(得分:0)

使用此代码

final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.ms_pdf_viewer_password_layout);
dialog.setTitle("Any Title You Want");
EditText editText = (EditText) dialog.findViewById(R.id.editText);

现在尝试使用onClickListener。

答案 2 :(得分:0)

我终于通过使用这一行来解决它

 EditText editText = dialog.findViewById(R.id.edittext); 

之后

  dialog.show().