Android : clear focus on edittext when activity st

2019-02-11 01:34发布

I've some settings page in my app. Once the activity gets starts directly it focus to edittext and i used following code to clear foucs.

<RelativeLayout 
     android:id="@+id/RequestFocusLayout"
     android:focusable="true"
     android:focusableInTouchMode="true"
     android:layout_width="0px"
     android:layout_height="0px"/>

and in java code

 RelativeLayout focuslayout = (RelativeLayout) findViewById(R.id.RequestFocusLayout);
 focuslayout.requestFocus();

The above code is working fine when activity starts at first time and if same activity starts again, automatically edittext get focus.

Can anyone help me to solve this issue.

7条回答
Evening l夕情丶
2楼-- · 2019-02-11 01:55

In the layout XML file, specify an imeOption on your EditText:

android:imeOptions="actionGo"

Next, add an action listener to your EditText in the Activity's java file

mYourEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_GO) {
            // hide virtual keyboard
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mYourEditText.getWindowToken(), 0);
            return true;
        }
        return false;
    }
});

Where mYourEditText is an EditText object

查看更多
该账号已被封号
3楼-- · 2019-02-11 01:57

Put the code to remove the focus in your onStart() method and it should work fine.

查看更多
The star\"
4楼-- · 2019-02-11 02:00
If Come back from other activity edittext get focused. 

put these line onStart() or on onReusme()

  RelativeLayout focuslayout = (RelativeLayout) findViewById(R.id.RequestFocusLayout);
 focuslayout.requestFocus();
查看更多
女痞
5楼-- · 2019-02-11 02:01

Me realy help only android:focusableInTouchMode="true" in my parent view group.

查看更多
男人必须洒脱
6楼-- · 2019-02-11 02:05

I used the solution shown up in this page but it didn't work. Add this attribute to your activity tag into AndroidManifest:

android:windowSoftInputMode="stateHidden"

It works perfectly.

查看更多
孤傲高冷的网名
7楼-- · 2019-02-11 02:08

If your EditText is a child of your RelativeLayout you can use android:descendantFocusability to request the focus:

<RelativeLayout 
     android:id="@+id/RequestFocusLayout"
     android:focusable="true"
     android:layout_width="0px"
     android:layout_height="0px" 
     android:descendantFocusability="beforeDescendants" 
     android:focusableInTouchMode="true" />
查看更多
登录 后发表回答