programing

Android에서 활동이 시작될 때 EditText가 집중되지 않도록 하는 방법은 무엇입니까?

muds 2023. 5. 31. 18:37
반응형

Android에서 활동이 시작될 때 EditText가 집중되지 않도록 하는 방법은 무엇입니까?

나는 있습니다.ActivityAndroid의 경우 두 가지 요소가 있습니다.

  1. EditText
  2. ListView

의 가언제 때.Activity 작시,EditText입력 포커스(커서 표시)가 즉시 표시됩니다.시작할 때 입력 포커스가 있는 컨트롤을 원하지 않습니다.노력했습니다.

EditText.setSelected(false);
EditText.setFocusable(false);

운이 없습니다.어떻게 하면 그들을 설득할 수 있습니까?EditText자신을 선택하지 않는 것은Activity시작?

하기 그추 가android:focusableInTouchMode="true"그리고.android:focusable="true" 레이아웃 상레이웃예아위예)으로 합니다.LinearLayout또는ConstraintLayout다음 예와 같이 문제를 해결할 수 있습니다.

<!-- 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가 명시적으로 하지 않았을 때 .EditText(그 결과 키보드를 엽니다.)

키보드의 가상키경을 하십시오.AndroidManifest.xml <activity> 요소 설명서.

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();

Guillaume Perrot의 좋은 논평:

android:descendantFocusability="beforeDescendants"기본값인 것 같습니다(기본값은 0).를 추가하는 것만으로 작동합니다.android:focusableInTouchMode="true".

정말로, 우리는 볼 수 있습니다.beforeDescendants는 서기값설 됩니다.ViewGroup.initViewGroup()방법(Android 2.2.2).하지만 0과 같지는 않습니다.ViewGroup.FOCUS_BEFORE_DESCENDANTS = 0x20000;

기욤 덕분에.

제가 찾은 유일한 해결책은:

  • 선형 레이아웃 만들기(다른 종류의 레이아웃이 작동할지 여부를 알 수 없음)
  • 합니다.android:focusable="true"그리고.android:focusableInTouchMode="true"

리고그.EditText 못할입니다.

문제는 오직 내가 볼 수 있는 부동산에서 오는 것 같습니다.XML form배치의.

내 선언의 끝에 있는 이 줄을 제거해야 합니다.EditTextXML 파일:

<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"/>

생성 시()

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);
}

그리고 마지막으로, 이력서()에서.

@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;
    }
});

이벤트를 사용하지 않는 등 거짓으로 반환하므로 포커스 동작이 정상적으로 진행됩니다.

늦었지만 간단한 답변은 XML의 상위 레이아웃에 추가하면 됩니다.

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

도움이 되었다면 투표하세요!해피 코딩 :)

여러 답변을 개별적으로 시도했지만 여전히 텍스트 편집에 초점이 맞춰져 있습니다.저는 아래의 두 가지 솔루션을 함께 사용하여 겨우 해결했습니다.

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

(Silver https://stackoverflow.com/a/8639921/15695 참조)

제거

<requestFocus />

텍스트 편집 시

:floydaddict https://stackoverflow.com/a/9681809 )

이 해결책들 중 어느 것도 저에게 효과가 없었습니다.자동 포커스를 수정하는 방법은 다음과 같습니다.

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

간단한 솔루션:AndroidManifestActivity use use

android:windowSoftInputMode="stateAlwaysHidden"

"Focusable(포커스 가능)" 및 "Focusable in touch(터치 모드에서 포커스 가능)" 값을 첫 번째 값에서 true로 설정하면 됩니다.TextView의 시대의layout이러한 방식으로 활동이 시작될 때TextView초점이 맞춰지지만 그 특성상 화면에 초점이 맞춰지는 것을 볼 수 없으며, 물론 키보드도 표시되지 않습니다.

다음은 에서 저에게 효과가 있었습니다.Manifest을 쓰고 기쓰,,

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

저는 프로그래밍 방식으로 모든 분야에 명확하게 초점을 맞출 필요가 있었습니다.나는 방금 나의 기본 레이아웃 정의에 다음 두 개의 문을 추가했습니다.

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

바로 그겁니다.제 문제를 즉시 해결했습니다.올바른 방향을 가르쳐 주셔서 감사합니다, 실버.

더하다android:windowSoftInputMode="stateAlwaysHidden"의 .Manifest.xmljava.

원천

약만당당활동대해다에있가면다견지고른해를과 같은 다른 가 있다면,ListView다음 작업도 수행할 수 있습니다.

ListView.requestFocus(); 

의 신의에onResume()에서 editText.

저는 이 질문에 답했다는 것을 알지만 저에게 효과가 있는 대안적인 해결책을 제공하는 것뿐입니다.

첫 번째 편집 가능한 필드 전에 이 작업을 수행합니다.

<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();

음을추 다니합가에 합니다.onCreate방법:

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

부모 레이아웃에 이 줄 쓰기...

 android:focusableInTouchMode="true"

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;
}

늦었지만 도움이 될 수도 있습니다.맨를 만든 "" "" " " " " " " " 를 호출합니다.myDummyEditText.requestFocus()onCreate()

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

그것은 제가 예상한 대로 행동하는 것 같습니다.구성 변경 등을 처리할 필요가 없습니다.긴 텍스트 보기(지침)가 있는 활동에 필요했습니다.

네, 저도 같은 일을 했습니다. 초기 초점을 맞추는 '더미' 선형 레이아웃을 만듭니다.또한 한 번 스크롤한 후 사용자가 더 이상 포커스를 맞출 수 없도록 '다음' 포커스 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" />

이것을 문제 중심적인 관점 앞에 보기로 두면, 그것으로 끝입니다.

<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"/>

가장 간단한 작업은 Create:의 다른 보기에 초점을 맞춘 것입니다.

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

이렇게 하면 소프트 키보드가 나타나지 않고 편집 텍스트에서 깜박이는 커서가 없습니다.

이것이 가장 완벽하고 쉬운 해결책입니다.저는 항상 제 앱에서 이것을 사용합니다.
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

는 내에이코기다니록합 안에 .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.project"
    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>

키보드를 숨기는 가장 쉬운 방법은 setSoftInputMode를 사용하는 것입니다.

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

또는 InputMethodManager를 사용하여 키보드를 숨길 수 있습니다.

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

에서onCreate사용자의 활동을 추가합니다.clearFocus()텍스트 편집 요소에 있습니다.를 들면 를들면예,

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

포커스를 다른 요소로 전환하려면 다음을 사용합니다.requestFocus()그것에 관하여예를들면,

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

언급URL : https://stackoverflow.com/questions/1555109/how-to-stop-edittext-from-gaining-focus-when-an-activity-starts-in-android

반응형