Powstrzymaj EditText przed skupieniem się na uruchomieniu aktywności

Mam Activity W Androidzie, z dwoma elementami:

  1. EditText
  2. ListView

Po uruchomieniu my Activity, {[2] } natychmiast ma ustawioną ostrość wejściową (migający kursor). Nie chcę, aby jakakolwiek kontrola miała fokus wejściowy przy starcie. Próbowałem:

EditText.setSelected(false);
Bez powodzenia. Jak mogę przekonać EditText, aby nie wybierał się sam, gdy Activity się rozpocznie?
Author: Pankaj Lilan, 2009-10-12

30 answers

Doskonałe odpowiedzi od Luca i Marka jednak brakuje dobrej próbki kodu. Dodanie znacznika android:focusableInTouchMode="true" do <LinearLayout> jak w poniższym przykładzie rozwiąże problem.

<!-- 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"/>
 2107
Author: Morgan Christiansson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-27 21:33:34

Czy rzeczywisty problem polega na tym, że po prostu nie chcesz, aby w ogóle było skupione? A może nie chcesz, aby pokazywała wirtualną klawiaturę w wyniku skupienia EditText? Tak naprawdę nie widzę problemu z EditText z ustawianiem ostrości na start, ale zdecydowanie problemem jest otwarcie okna softInput, gdy użytkownik nie zażądał bezpośrednio skupienia się na EditText (i w rezultacie otworzy klawiaturę).

Jeśli jest to problem klawiatury wirtualnej, zobacz AndroidManifest.xml element dokumentacja.

android:windowSoftInputMode="stateHidden" - zawsze Ukryj Go podczas wchodzenia do aktywności.

Lub android:windowSoftInputMode="stateUnchanged" - nie zmieniaj tego (np. Nie pokazuj , jeśli nie jest już pokazany, ale jeśli był otwarty podczas wprowadzania aktywności, pozostaw otwarte).

 1585
Author: Joe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-11 17:02:33

Istnieje prostsze rozwiązanie. Ustaw te atrybuty w układzie nadrzędnym:

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

I teraz, gdy aktywność się rozpocznie, ten główny układ będzie domyślnie ustawiony.

Możemy również usunąć fokus z widoków potomnych w czasie wykonywania (np. po zakończeniu edycji potomnej), ponownie nadając fokus układowi głównemu, w ten sposób:

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

Dobry komentarz z Guillaume Perrot :

android:descendantFocusability="beforeDescendants" wydaje się być domyślnie (wartość całkowita to 0). Działa wystarczy dodać android:focusableInTouchMode="true".

Naprawdę widzimy, że beforeDescendants ustawione jako domyślne w metodzie ViewGroup.initViewGroup() (Android 2.2.2). Ale nie równa 0. ViewGroup.FOCUS_BEFORE_DESCENDANTS = 0x20000;

Dzięki Guillaume ' owi.
 1037
Author: Silver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-14 19:13:16

Jedyne rozwiązanie jakie znalazłem to:

  • Utwórz LinearLayout (Nie wiem, czy inne rodzaje layoutów będą działać)
  • Ustaw atrybuty android:focusable="true" i android:focusableInTouchMode="true"

I EditText nie uzyskają ostrości po rozpoczęciu aktywności

 394
Author: Luc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-21 22:30:47

Problem wydaje się pochodzić z właściwości, które widzę tylko w XML form układu.

Upewnij się, że usuniesz ten wiersz na końcu deklaracji z EditText znaczników XML:

<requestFocus />

To powinno dać coś takiego:

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

   //<requestFocus /> /* <-- without this line */
</EditText>
 71
Author: floydaddict,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-21 21:17:10

Korzystając z informacji dostarczonych przez inne plakaty, użyłem następującego rozwiązania:

W układzie 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"/>

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

I wreszcie, w onResume()

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

    //do not give the editbox focus automatically when activity starts
    mAutoCompleteTextView.clearFocus();
    mLinearLayout.requestFocus();
}
 64
Author: Someone Somewhere,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-24 22:21:35

Poniższy tekst powstrzyma edittext przed skupieniem się podczas tworzenia, ale chwyci go, gdy go dotkniesz.

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

Więc ustawiasz Focusable na false w xml, ale klucz jest w Javie, do którego dodajesz następujący listener:

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

Ponieważ zwracasz false, tzn. nie konsumujesz zdarzenia, zachowanie skupienia będzie przebiegało normalnie.

 60
Author: MinceMan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-24 21:43:56

Spróbuj clearFocus () zamiast setSelected(false). Każdy widok w Androidzie ma zarówno ostrość, jak i możliwość wyboru i myślę, że chcesz po prostu wyczyścić ostrość.

 59
Author: Konklone,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-22 05:09:00

Próbowałem kilka odpowiedzi indywidualnie, ale nacisk jest nadal na EditText. Udało mi się go rozwiązać tylko za pomocą dwóch z poniższych rozwiązań razem.

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

(odniesienie ze srebra https://stackoverflow.com/a/8639921/15695 )

I usunąć

 <requestFocus />

At EditText

( Odniesienie z floydaddict https://stackoverflow.com/a/9681809 )

 45
Author: Lee Yi Hong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-10 05:49:44

Żadne z tych rozwiązań nie zadziałało. Jak naprawiam autofocus to:

<activity android:name=".android.InviteFriendsActivity" android:windowSoftInputMode="adjustPan">
    <intent-filter >
    </intent-filter>
</activity>
 38
Author: rallat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-30 16:37:52

Proste rozwiązanie: In AndroidManifest in Activity Tag use

android:windowSoftInputMode="stateAlwaysHidden"
 33
Author: Sergey Sheleg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-27 10:05:40

Możesz po prostu ustawić "focusable" i "focusable in touch mode" na wartość true na pierwszym TextView z layout. W ten sposób po uruchomieniu aktywności TextView będzie skupiona, ale ze względu na swoją naturę nie zobaczysz nic skupionego na ekranie i oczywiście nie będzie wyświetlana Żadna klawiatura...

 30
Author: Zeus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-27 18:13:21

Następujące zadziałały dla mnie w Manifest. Napisz,

<activity
android:name=".MyActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>
 29
Author: Babar Sanah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-27 10:05:28

Musiałem programowo wyczyścić fokus ze wszystkich pól. Właśnie dodałem następujące dwa stwierdzenia do mojej definicji głównego układu.

myLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
myLayout.setFocusableInTouchMode(true);
To wszystko. Natychmiast naprawiłem mój problem. Dzięki, Silver, za wskazówkę we właściwym kierunku.
 25
Author: jakeneff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-27 23:35:28

Dodaj android:windowSoftInputMode="stateAlwaysHidden" do znacznika aktywności pliku Manifest.xml.

Źródło

 24
Author: prgmrDev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-27 10:04:40

Najprostsza odpowiedź, wystarczy dodać to w układzie nadrzędnym XML.

android:focusable="true" 
android:focusableInTouchMode="true"
 24
Author: Rishabh Saxena,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-18 06:14:56

Jeśli masz inne spojrzenie na swoją aktywność jak ListView, Możesz również zrobić:

ListView.requestFocus(); 

W twoim onResume(), aby złapać ostrość z editText.

Wiem, że odpowiedź na to pytanie została udzielona, ale po prostu znalazłem alternatywne rozwiązanie, które zadziałało dla mnie:)

 19
Author: Sid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-27 18:11:18

Spróbuj tego przed pierwszym edytowalnym polem:

<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();
 18
Author: Jack Slater,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-12 00:41:21

Dodaj następujący tekst w metodzie onCreate:

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
 18
Author: Vishal Raj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-27 10:04:26

Ponieważ Nie lubię zanieczyszczać XML czymś, co jest związane z funkcjonalnością, stworzyłem tę metodę, która "transparentnie" kradnie fokus z pierwszego widoku, a następnie upewnia się, że usuwa się, gdy jest to konieczne!

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;
}
 13
Author: Takhion,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-24 13:26:14

Spóźniony, ale może pomocny. Utwórz atrapę EditText u góry układu, a następnie wywołaj myDummyEditText.requestFocus() w onCreate()

<EditText android:id="@+id/dummyEditTextFocus" 
android:layout_width="0px"
android:layout_height="0px" />
Wygląda na to, że zachowuję się tak, jak oczekuję. Nie ma potrzeby obsługi zmian konfiguracji itp. Potrzebowałem tego do działania z długim TextView (instrukcje).
 12
Author: Jim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-02-13 01:58:17

Tak, zrobiłem to samo - stworzyłem 'atrapowy' układ liniowy, który dostaje początkową ostrość. Co więcej, ustawiłem' next ' focus ID, aby użytkownik nie mógł skupić się już po przewinięciu raz:

<LinearLayout 'dummy'>
<EditText et>

dummy.setNextFocusDownId(et.getId());

dummy.setNextFocusUpId(et.getId());

et.setNextFocusUpId(et.getId());
Dużo pracy, żeby pozbyć się skupienia na widoku..

Thanks

 12
Author: mark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-27 18:13:04

Zapisz tę linię w układzie nadrzędnym...

 android:focusableInTouchMode="true"
 11
Author: Vishal Vaishnav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-26 09:52:46

Dla mnie to, co działało na wszystkich urządzeniach, To:

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

Po prostu postaw to jako Widok przed problematycznym, skupionym widokiem, i to wszystko.

 10
Author: android developer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-14 08:02:14

To idealne i najprostsze rozwiązanie.Zawsze używam tego w mojej aplikacji.

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
 9
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-31 09:27:09

Najprostszą rzeczą, jaką zrobiłem, jest ustawienie ostrości na innym widoku w onCreate:

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

To zatrzymało pojawianie się miękkiej klawiatury i nie migało kursora w edytorze.

 8
Author: Lumis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-03 06:57:31

Wpisz ten kod w pliku Manifest w Activity, gdzie nie chcesz otwierać klawiatury.

android:windowSoftInputMode="stateHidden"

Plik manifestu:

 <?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>
 7
Author: Tarit Ray,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-15 07:21:33
<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"/>
 7
Author: atul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-31 18:41:46

W onCreate swojej aktywności, po prostu dodaj use clearFocus() na elemencie EditText. Na przykład,

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

I jeśli chcesz przekierować fokus na inny element, użyj requestFocus() na tym. Na przykład,

button = (Button) findViewById(R.id.button);
button.requestFocus();
 6
Author: Compaq LE2202x,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-23 10:42:18

Można to osiągnąć, tworząc atrapę EditText z szerokością i wysokością układu ustawioną na 0dp i żądając ustawienia ostrości dla tego widoku. Dodaj następujący fragment kodu w układzie xml:

<EditText
    android:id="@+id/editText0"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:hint="@string/dummy"
    android:ems="10" 
    >
     <requestFocus />
    </EditText>
 6
Author: Ish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-27 10:04:54