문제

Activity 안드로이드와 함께,두 가지 요소:

  1. EditText
  2. ListView

때 나 Activity 가 시작되면, EditText 즉시 입력 포커스(번쩍이는 커서).나는 원하지 않는 어떤 제어를 입력 초점에서 시작합니다.I tried:

EditText.setSelected(false);

습니다.할 수 있는 방법을 설득 EditText 를 선택하지 않으면 자동 Activity 시작?

도움이 되었습니까?

해결책

LUC와 Mark의 훌륭한 답변이지만 좋은 코드 샘플이 누락되었습니다. 태그 추가 android:focusableInTouchMode="true" 에게 <LinearLayout> 다음 예제와 마찬가지로 문제가 해결됩니다.

<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
    android:focusable="true" 
    android:focusableInTouchMode="true"
    android:layout_width="0px" 
    android:layout_height="0px"/>

<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this component
to prevent the dummy from receiving focus again -->
<AutoCompleteTextView android:id="@+id/autotext"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:nextFocusUp="@id/autotext" 
    android:nextFocusLeft="@id/autotext"/>

다른 팁

당신이 그것이 전혀 집중하기를 원하지 않는 실제 문제입니까? 아니면 초점을 맞춘 결과로 가상 키보드를 보여주기를 원하지 않습니다. EditText? 나는 실제로 문제를 보지 못한다 EditText 시작에 집중하지만 사용자가 명시 적으로 집중하도록 요청하지 않았을 때 SoftInput 창을 열어 두는 것은 확실히 문제입니다. EditText (결과적으로 키보드를 엽니 다).

가상 키보드의 문제라면 AndroidManifest.xml u003Cactivity>요소 선적 서류 비치.

android:windowSoftInputMode="stateHidden" - 활동에 들어갈 때는 항상 숨기십시오.

또는 android:windowSoftInputMode="stateUnchanged" - 변경하지 마십시오 (예 : 그렇지 않습니다 보여 주다 아직 표시되지 않았지만 활동에 들어갈 때 열려 있으면 열어 두십시오).

더 간단한 솔루션이 있습니다. 이 속성을 부모 레이아웃에서 설정하십시오.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true" >

그리고 이제 활동이 시작되면이 메인 레이아웃은 기본적으로 초점을 맞 춥니 다.

또한 런타임 (예 : 어린이 편집 후 아동 편집 후)에서 초점을 제거 할 수 있습니다.

findViewById(R.id.mainLayout).requestFocus();

좋은 의견 ~에서 기 illa perrot:

android:descendantFocusability="beforeDescendants" 기본값 인 것 같습니다 (정수 값은 0). 추가하여 작동합니다 android:focusableInTouchMode="true".

실제로, 우리는 그것을 볼 수 있습니다 beforeDescendants 기본값으로 설정합니다 ViewGroup.initViewGroup() 방법 (Android 2.2.2). 0과 같지 않습니다. ViewGroup.FOCUS_BEFORE_DESCENDANTS = 0x20000;

기 illa 덕분에 감사합니다.

내가 찾은 유일한 해결책은 다음과 같습니다.

  • a LinearLayout (다른 종류의 레이아웃이 작동한다면 나는 몰라요)
  • 속성을 설정하십시오 android:focusable="true" 그리고 android:focusableInTouchMode="true"

그리고 EditText 활동을 시작한 후에는 초점을 맞추지 않습니다

문제는 내가 볼 수있는 재산에서 나온 것 같습니다. XML form 레이아웃의.

선언 끝 에서이 줄을 제거하십시오. EditText XML 태그 :

<requestFocus />

그것은 그런 것을 주어야합니다.

<EditText
   android:id="@+id/emailField"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:inputType="textEmailAddress">

   //<requestFocus /> /* <-- without this line */
</EditText>

다른 포스터가 제공 한 정보를 사용하여 다음 솔루션을 사용했습니다.

레이아웃 XML에서

<!-- Dummy item to prevent AutoCompleteTextView from receiving focus -->
<LinearLayout
    android:id="@+id/linearLayout_focus"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_width="0px"
    android:layout_height="0px"/>

<!-- AUTOCOMPLETE -->
<AutoCompleteTextView
    android:id="@+id/autocomplete"
    android:layout_width="200dip"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dip"
    android:inputType="textNoSuggestions|textVisiblePassword"/>

oncreate ()에서

private AutoCompleteTextView mAutoCompleteTextView;
private LinearLayout mLinearLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylayout);

    //get references to UI components
    mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
    mLinearLayout = (LinearLayout) findViewById(R.id.linearLayout_focus);
}

그리고 마지막으로 onresume ()에서

@Override
protected void onResume() {
    super.onResume();

    //do not give the editbox focus automatically when activity starts
    mAutoCompleteTextView.clearFocus();
    mLinearLayout.requestFocus();
}

노력하다 Clearfocus () 대신에 setSelected(false). Android의 모든 견해에는 초점과 선택성이 모두 있으며 초점을 정리하고 싶다고 생각합니다.

다음은 EditText가 생성 될 때 초점을 맞추지 못하게하지만 만질 때 잡을 수 있습니다.

<EditText
    android:id="@+id/et_bonus_custom"
    android:focusable="false" />

따라서 XML에서 False에 집중할 수 있지만 키는 Java에 있으며 다음 리스너를 추가합니다.

etBonus.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.setFocusable(true);
        v.setFocusableInTouchMode(true);
        return false;
    }
});

당신이 거짓을 반환하고, 즉 사건을 소비하지 않기 때문에, 초점 행동은 정상처럼 진행됩니다.

려고 했던 여러 답변을 개별적으로 그 초점은 아직도에 EditText.나는 단지를 해결하기 위해 관리하여 그것을 사용하여 두 개의 아래 솔루션을 함께합니다.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/mainLayout"
  android:descendantFocusability="beforeDescendants"
  android:focusableInTouchMode="true" >

(참조에서 실버 https://stackoverflow.com/a/8639921/15695 )

고를 제거

 <requestFocus />

에 EditText

(참조에서 floydaddict https://stackoverflow.com/a/9681809 )

늦었지만 가장 간단한 대답은 XML의 상위 레이아웃에 추가하십시오.

android:focusable="true" 
android:focusableInTouchMode="true"

그것이 당신을 도왔다면 upvote! 행복한 코딩 :)

이 솔루션 중 어느 것도 저에게 도움이되지 않았습니다. 내가 자동 초점을 고치는 방법은 다음과 같습니다.

<activity android:name=".android.InviteFriendsActivity" android:windowSoftInputMode="adjustPan">
    <intent-filter >
    </intent-filter>
</activity>

간단한 해결책 : in AndroidManifest 안에 Activity 태그 사용

android:windowSoftInputMode="stateAlwaysHidden"

방금 설정할 수 있습니다 "집중 가능" 그리고 "터치 모드에서 집중 가능" 첫 번째에 참으로 가치를 평가합니다 TextViewlayout. 이런 식으로 활동이 시작될 때 TextView 초점을 맞출 것이지만, 그 본질로 인해 화면에 중점을 두지 않을 것입니다. 물론 아니요 키보드 표시 ...

다음은 나를 위해 일했습니다 Manifest. 쓰다 ,

<activity
android:name=".MyActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>

프로그래밍 방식으로 모든 분야에서 초점을 깨끗하게해야했습니다. 방금 주요 레이아웃 정의에 다음 두 문장을 추가했습니다.

myLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
myLayout.setFocusableInTouchMode(true);

그게 다야. 내 문제를 즉시 수정했습니다. 올바른 방향으로 나를 지적 해 주셔서 감사합니다.

추가하다 android:windowSoftInputMode="stateAlwaysHidden" 활동 태그에서 Manifest.xml 파일.

원천

당신의 활동에 대한 또 다른 견해가있는 경우 ListView, 당신은 또한 할 수 있습니다 :

ListView.requestFocus(); 

당신의 onResume() The에서 초점을 맞추기 위해 editText.

나는이 질문에 대한 답변이 있다는 것을 알고 있지만 단지 나를 위해 일한 대체 솔루션을 제공하는 것뿐입니다 :)

다음을 추가하십시오 onCreate 방법:

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

첫 번째 편집 가능한 필드 전에 이것을 시도하십시오.

<TextView  
        android:id="@+id/dummyfocus" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:text="@string/foo"
        />

----

findViewById(R.id.dummyfocus).setFocusableInTouchMode(true);
findViewById(R.id.dummyfocus).requestFocus();

기능성과 관련된 것으로 XML을 오염시키는 것을 좋아하지 않기 때문에 첫 번째 초점을 맞춘보기에서 초점을 "투명하게"훔친 다음 필요할 때 스스로를 제거하는이 방법을 만들었습니다!

public static View preventInitialFocus(final Activity activity)
{
    final ViewGroup content = (ViewGroup)activity.findViewById(android.R.id.content);
    final View root = content.getChildAt(0);
    if (root == null) return null;
    final View focusDummy = new View(activity);
    final View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View view, boolean b)
        {
            view.setOnFocusChangeListener(null);
            content.removeView(focusDummy);
        }
    };
    focusDummy.setFocusable(true);
    focusDummy.setFocusableInTouchMode(true);
    content.addView(focusDummy, 0, new LinearLayout.LayoutParams(0, 0));
    if (root instanceof ViewGroup)
    {
        final ViewGroup _root = (ViewGroup)root;
        for (int i = 1, children = _root.getChildCount(); i < children; i++)
        {
            final View child = _root.getChildAt(i);
            if (child.isFocusable() || child.isFocusableInTouchMode())
            {
                child.setOnFocusChangeListener(onFocusChangeListener);
                break;
            }
        }
    }
    else if (root.isFocusable() || root.isFocusableInTouchMode())
        root.setOnFocusChangeListener(onFocusChangeListener);

    return focusDummy;
}

늦었지만 도움이 될 수도 있습니다. 레이아웃 상단에 더미 edittext를 만들고 전화하십시오. myDummyEditText.requestFocus() 안에 onCreate()

<EditText android:id="@+id/dummyEditTextFocus" 
android:layout_width="0px"
android:layout_height="0px" />

그것은 내가 예상 한대로 행동하는 것 같습니다. 구성 변경 등을 처리 할 필요가 없습니다. 긴 TextView (지침)가있는 활동에는이 작업이 필요했습니다.

예, 나는 같은 일을했습니다 - 초기 초점을 맞춘 '더미'선형 레이아웃을 만듭니다. 또한 'Next'Focus ID를 설정하여 사용자가 한 번 스크롤 한 후 더 이상 집중할 수 없습니다.

<LinearLayout 'dummy'>
<EditText et>

dummy.setNextFocusDownId(et.getId());

dummy.setNextFocusUpId(et.getId());

et.setNextFocusUpId(et.getId());

견해에 초점을 맞추기 위해 많은 작업이 ..

감사

저에게는 모든 장치에서 작동 한 것은 다음과 같습니다.

    <!-- fake first focusable view, to allow stealing the focus to itself when clearing the focus from others -->

    <View
    android:layout_width="0px"
    android:layout_height="0px"
    android:focusable="true"
    android:focusableInTouchMode="true" />

문제가되는 시야 앞에 이것을보기로 두십시오.

부모 레이아웃 에이 줄을 쓰십시오 ...

 android:focusableInTouchMode="true"

이것은 완벽하고 가장 쉬운 솔루션입니다. 저는 항상 내 앱에서 사용합니다.

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

내가 한 가장 간단한 일은 OnCreate의 다른 견해에 초점을 맞추는 것입니다.

    myView.setFocusableInTouchMode(true);
    myView.requestFocus();

이로 인해 소프트 키보드가 올라가고 EditText에는 커서가 깜박이지 않았습니다.

이 코드를 안에 작성하십시오 Manifest 파일 Activity 키보드를 열고 싶지 않은 곳.

android:windowSoftInputMode="stateHidden"

매니페스트 파일 :

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.projectt"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="24" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
         <activity
            android:name=".Splash"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Login"
            **android:windowSoftInputMode="stateHidden"**
            android:label="@string/app_name" >
        </activity>

    </application>

</manifest>
<TextView
    android:id="@+id/TextView01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit="marquee_forever"
    android:focusable="true"
    android:focusableInTouchMode="true"
    style="@android:style/Widget.EditText"/>

~에 onCreate 당신의 활동의 경우 사용을 추가하십시오 clearFocus() EditText 요소에. 예를 들어,

edittext = (EditText) findViewById(R.id.edittext);
edittext.clearFocus();

초점을 다른 요소로 전환하려면 사용하십시오. requestFocus() 그것에. 예를 들어,

button = (Button) findViewById(R.id.button);
button.requestFocus();

더미를 만들어이를 달성 할 수 있습니다 EditText 레이아웃 너비와 높이가 설정되어 있습니다 0dp, 그리고 그 견해에 초점을 맞추십시오. XML 레이아웃에 다음 코드 스 니펫을 추가하십시오.

<EditText
    android:id="@+id/editText0"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:hint="@string/dummy"
    android:ems="10" 
    >
     <requestFocus />
    </EditText>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top