2016-04-28 5 views
26

Когда я помещаю RecycleView внутри вложенного прокрутки, экран всегда переместится вверху recycleview, а не вверху страницы. Вот простой пример.RecycleView крадет фокус, когда внутри NestedScrollView

расположения XML:

<?xml version="1.0" encoding="utf-8"?> 
<layout xmlns:tools="http://schemas.android.com/tools" 
    xmlns:android="http://schemas.android.com/apk/res/android"> 
<android.support.v4.widget.NestedScrollView 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 
     <RelativeLayout 
      android:layout_width="match_parent" 
      android:layout_height="350dp" 
      android:background="@android:color/holo_blue_dark"/> 
     <android.support.v7.widget.RecyclerView 
      android:id="@+id/recycleView" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" /> 
    </LinearLayout> 
</android.support.v4.widget.NestedScrollView> 
</layout> 

активность с фиктивным адаптером:

public class RecycleViewTestActivity extends AppCompatActivity { 

public static class ExampleAdapter extends RecyclerView.Adapter<ExampleViewHolder> { 

    private Context context; 

    public ExampleAdapter(Context context) { 
     this.context = context; 
    } 

    @Override 
    public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     TextView view = new TextView(context); 
     view.setText("Test"); 
     return new ExampleViewHolder(view); 
    } 

    @Override 
    public void onBindViewHolder(ExampleViewHolder holder, int position) { 

    } 

    @Override 
    public int getItemCount() { 
     return 100; 
    } 
} 

public static class ExampleViewHolder extends RecyclerView.ViewHolder { 

    public ExampleViewHolder(View itemView) { 
     super(itemView); 
    } 
} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_rectest); 
    RecyclerView view = (RecyclerView) findViewById(R.id.recycleView); 
    view.setNestedScrollingEnabled(false); 
    view.setLayoutManager(new LinearLayoutManager(this)); 
    ExampleAdapter adapter = new ExampleAdapter(this); 
    view.setAdapter(adapter); 
} 

} 

В этом примере у меня есть 350dp высокого пустого вида на recycleview, потому что вы должны иметь некоторое содержание над RecycleView для это очевидно. RecycleView itestelf содержит 100 фиктивных текстовых просмотров.

После того, как вы запустите действие, прокрутка находится вверху RecycleView, а не вверху страницы. Это должно быть что-то внутри LinearLayoutManager, но havent действительно выглядел еще.

Любые идеи, как это решить?

+0

[та же проблема Проверить решение здесь] (http://stackoverflow.com/a/41481237/1993001) –

ответ

72

Сделайте свой верхний вид Focusable. «RecyclerView имеет« focusableOnTouchMode », установленный в true, чтобы обрабатывать изменения фокуса его детей во время компоновки». Релевантно discussion of the issue.

Пример:

<android.support.v4.widget.NestedScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent""> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:focusableInTouchMode="true" 
     android:orientation="vertical"> 

     <View 
      android:id="@+id/someView" 
      android:layout_width="wrap_content" 
      android:layout_height="350dp"/> 

     <android.support.v7.widget.RecyclerView 
      android:id="@+id/recyclerView" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content"/> 

    </LinearLayout> 
</android.support.v4.widget.NestedScrollView> 
+1

Спасибо, это действительно решает эту проблему. – breakline

+3

Это сработало и для меня. Просто поставьте: android: focusable = "true" android: focusableInTouchMode = "true" в любом представлении, являющемся родителем вашего RecyclerView, и которое должно его решить. – Lancelot

+1

Спасибо lottttttt @ Amagi82. Ты спас мой день – MashukKhan

0

ли это так:

LinearLayoutManager lm = new LinearLayoutManager(this); 
lm.setAutoMeasureEnabled(true); 
view.setLayoutManager(lm) 
+0

К сожалению, это не работает для меня, такой же результат – breakline

+0

добавьте это в свой recyclerView в XML: app: layout_behavior = "@ string/appbar_scrolling_view_behavior" –

+0

сделал это, или есть какие-либо проблемы? –

6

Для меня принял ответ не работал. Я решить эту проблему путем добавления этого атрибута для родителей:

android:descendantFocusability="blocksDescendants"

+0

это сработало для меня. Я использовал просмотр recycler в режиме просмотра прокрутки. спасибо –

+0

У меня был такой же макет, как @GulnazGhanchi. Это сработало для меня :-) –

+0

Отлично, это также работает при использовании горизонтального RecyclerView (ов) внутри вертикального RecyclerView.Элемент будет украсть фокус, когда данные будут привязаны, и заставит список делать небольшие «прыжки», что снижает производительность. Работает как шарм для добавления android: descendantFocusability = "blocksDescendants" в корень макета Horizontals ReyclerView. – Slickelito

1

Спасибо @ Amagi82. Вы ответили мне, но этого было недостаточно. Я добавил еще 2 атрибута. Это работает для меня:

<android.support.v4.widget.NestedScrollView 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent""> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:focusableInTouchMode="true" 
    android:focusable="true" 
    android:descendantFocusability="blocksDescendants" 
    android:orientation="vertical"> 

    <View 
     android:id="@+id/someView" 
     android:layout_width="wrap_content" 
     android:layout_height="350dp"/> 

    <android.support.v7.widget.RecyclerView 
     android:id="@+id/recyclerView" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"/> 

</LinearLayout>