Android Button always takes two clicks to fire onClick()

有些话、适合烂在心里 提交于 2021-02-11 15:48:53

问题


I have a RelativeLayout inside of a ScrollView that contains a Button and some TextViews and EditTexts.

In my xml layout file, I am defining android:onClick but it always takes two clicks of the button to fire the event. The button always gets the focus on the first click and fires the onClick event on the second click. I have tried setting focusable and focusableInTouchMode both to false but the behavior doesn't change.

Here is my layout file:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".DensityActivity" >

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
        ...

        <TextView
        ...

        <TextView
        ...

        <EditText
        ...

        <Button
            android:id="@+id/ad_button_calculate"
            android:layout_width="112dp"
            android:layout_height="wrap_content"
            android:layout_below="@id/ad_edit_obs_temp"
            android:layout_alignParentRight="true"
            android:layout_marginTop="20pt"
            android:paddingLeft="6pt"
            android:onClick="onClick"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:text="@string/button_calculate" />

        <TextView
        ...

    </RelativeLayout>
</ScrollView>

Any ideas or suggestions as to why the focusable and focusableInTouchMode don't seem to do anything?

I thought it might be my onClick() method not doing what it should so I reduced it to something simple just to see and it behaves the same. Here is my simplified onClick():

public void onClick(View view) {

    new AlertDialog.Builder(this).setTitle("Argh").setMessage("Watch out!").setNeutralButton("Close", null).show();

}

回答1:


OK, I found it. It was, of course, my own mistake. At the end of my onCreate method I was doing this:

// Set the focus to the calculate button so the keyboard won't show up automatically 
Button calcButton = (Button)findViewById( R.id.ac_button_calculate );
calcButton.setFocusable( true );
calcButton.setFocusableInTouchMode( true ); 
calcButton.requestFocus();

So of course, no matter what I did in my xml file, I was overriding it in my code. Instead, I used this to hide the keyboard:

getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN );

Which works great.



来源:https://stackoverflow.com/questions/17451422/android-button-always-takes-two-clicks-to-fire-onclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!