3

我有一个 EditText 字段。当我在其上设置 onClickListener 时,它首先需要将焦点放在该字段上,然后单击以调用侦听器。所以实际上是两次点击调用监听器。如何解决此问题以从第一次点击开始工作?我不想将 focusable 设置为 false,因为那样程序将无法运行。

4

4 回答 4

10

正如其他人所说,第一次触摸聚焦视图,第二次触摸“点击”它。与其执行OnClickListener,不如执行OnFocusChangeListener。例如

EditText edittext = (EditText)findViewById(R.id.myedittext);
edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(hasFocus) {
            //handle your situation here
        }
    }
});
于 2012-05-14T17:33:25.483 回答
1

当在 android 中触摸 EditText 时,首先它的焦点会改变。OnFocusChangeListener 第一次工作。

之后,onClickListener 每次都有效。

所以,如果你想在 EditText 监听器上实现一些东西,最好实现setOnTouchListener

每次它都会起作用。

于 2014-11-17T05:35:53.500 回答
0

我不完全理解您所说的两次单击以调用侦听器的意思。但是,如果 OnClick 方法被调用了两次,而您只希望代码运行一次,则可以创建一个标志作为成员变量来跟踪代码是否已经运行。例如,在初始化firstTime为之后true,在你的onClick方法中有这样的东西:

if (firstTime) {
  // Put code that you want executed once here
  firstTime = false;
}
else {
  firstTime = true;  // Second time: reset the flag
}
于 2012-05-14T16:55:55.270 回答
0

<requestFocus />

在您的 xml 中的编辑文本中。试试看,可能对你有帮助

    <EditText
            android:id="@+id/edtTxtEmail1"
            android:layout_width="240dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:inputType="textEmailAddress"
            android:hint="Email ID" >
            <requestFocus />
        </EditText>
于 2012-05-14T17:22:58.707 回答