2016-07-12 2 views
1

У меня проблема, которая сводит меня с ума. В основном это простой RecyclerView, который отображает карту. Уже есть много сообщений, которые я проверил. Я назначил LayoutManager, как указано здесь (RecyclerView Not Displaying Any CardView Items), я реализовал метод getItemCount, как описано здесь (card view not showing up), и я изменил на следующие версии (изменение версии была предложена здесь RecyclerView of cards not showing anything):CardView не показан в RecyclerView

compile 'com.android.support:support-v4:24.0.0' 
compile 'com.android.support:cardview-v7:24.0.0' 
compile 'com.android.support:recyclerview-v7:24.0.0' 

Я также сделал notifyDataSetChanged(), как указано здесь (RecyclerView Not Displaying Any CardView Items). Однако ничего не исправлялось для меня.

У меня есть активность, которая имеет следующий код (только соответствующие разделы, getDummyData возвращает список с 1 фиктивными данными):

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext()); 

    setContentView(R.layout.activity_overview); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    RecyclerView rv = (RecyclerView) findViewById(R.id.rv); 
    rv.setHasFixedSize(true); 
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); 
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); 
    rv.setLayoutManager(linearLayoutManager); 

    RVAdapter adapter = new RVAdapter(getDummyData()); 
    rv.setAdapter(adapter); 
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
        .setAction("Action", null).show(); 
     } 
    }); 
    adapter.notifyDataSetChanged(); 

} 


public class RVAdapter extends RecyclerView.Adapter<RVAdapter.DocumentViewHolder> { 

    List<Document> DocumentList; 

    public RVAdapter(List<Document> Documents) { 
     this.DocumentList = Documents; 
    } 

    @Override 
    public DocumentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.document_item, parent, false); 
     DocumentViewHolder pvh = new DocumentViewHolder(v); 
     return pvh; 
    } 

    @Override 
    public void onBindViewHolder(DocumentViewHolder DocumentViewHolder, int i) { 
     DocumentViewHolder.Date.setText(DocumentList.get(i).getCreatedFormatted()); 
     DocumentViewHolder.participants.setText(DocumentList.get(i).getParticipants(getApplicationContext())); 
     DocumentViewHolder.counterOfItems.setText(DocumentList.get(i).getcounterOfItems(getApplicationContext()) + StringUtils.EMPTY); 
    } 

    @Override 
    public void onAttachedToRecyclerView(RecyclerView recyclerView) { 
     super.onAttachedToRecyclerView(recyclerView); 
    } 

    @Override 
    public int getItemCount() { 

     //return DocumentList.size(); 
    return 1; 
    } 

    public class DocumentViewHolder extends RecyclerView.ViewHolder { 
     TextView Date; 
     TextView participants; 
     TextView ideasPreview; 
     TextView counterOfItems; 
     ImageView Photo; 

     public DocumentViewHolder(View itemView) { 
      super(itemView); 
      Date = (TextView) itemView.findViewById(R.id._date); 
      participants = (TextView) itemView.findViewById(R.id.participants); 
      ideasPreview = (TextView) itemView.findViewById(R.id.ideas_preview); 
      counterOfItems = (TextView) itemView.findViewById(R.id.counter_of_items); 
      Photo = (ImageView) itemView.findViewById(R.id._photo); 
     } 
    } 


} 

И у меня есть Document_item - XML:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical"> 

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto" 
    android:id="@+id/card_view" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    card_view:cardCornerRadius="@dimen/_card_corner"> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal"> 

     <ImageView 
      android:id="@+id/_photo" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_weight="0.25" /> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:gravity="center_horizontal" 
      android:orientation="vertical" 
      android:paddingBottom="@dimen/activity_vertical_margin" 
      android:paddingEnd="@dimen/activity_horizontal_margin" 
      android:paddingStart="@dimen/activity_horizontal_margin" 
      android:paddingTop="@dimen/activity_vertical_margin"> 

      <TextView 
       android:id="@+id/_date" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="21st June 2016" /> 

      <TextView 
       android:id="@+id/participants" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="Thomas, Christian and Johann" /> 

      <TextView 
       android:id="@+id/counter_of_items" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="Thomas, Christian and Johann" /> 

      <TextView 
       android:id="@+id/ideas_preview" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="Hello, Test, Test, Test" /> 

     </LinearLayout> 
    </LinearLayout> 
</android.support.v7.widget.CardView> 
</LinearLayout> 

Xml этого вида выглядит так:

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.CoordinatorLayout  
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:fitsSystemWindows="true" 
tools:context="com.chmaurer.idea.OverviewActivity"> 

<android.support.design.widget.AppBarLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:theme="@style/AppTheme.AppBarOverlay"> 

    <android.support.v7.widget.Toolbar 
     android:id="@+id/toolbar" 
     android:layout_width="match_parent" 
     android:layout_height="?attr/actionBarSize" 
     android:background="?attr/colorPrimary" 
     app:popupTheme="@style/AppTheme.PopupOverlay" /> 

</android.support.design.widget.AppBarLayout> 

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

<android.support.design.widget.FloatingActionButton 
    android:id="@+id/fab" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="bottom|end" 
    android:layout_margin="@dimen/fab_margin" 
    android:src="@drawable/ic_playlist_add_white_24dp" /> 

</android.support.design.widget.CoordinatorLayout> 

Код компилируется и исполняется нормой lly, но карты не отображаются. Я попробовал несколько часов для себя сейчас, но это, безусловно, той точка, где я был бы рад иметь намек ...

ответ

1

Ваш код хорошо, Проблема с файлом верстки: document_item.xml:

<LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal"> 

     <ImageView 
      android:id="@+id/_photo" 
      android:layout_width="wrap_content" -->mistake 
      android:layout_height="wrap_content" 
      android:layout_weight="0.25" /> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" -->mistake 
      android:gravity="center_horizontal" 
      android:orientation="vertical" 
      ... 

Второй LinearLayout получает свою высоту от родителя (первый LinearLayout), а первый получает свою высоту от своего единственного ребенка: ImageView (поэтому без набора drawable, высота второго макета будет равна нулю!), Если вы установите drawable для ImageViewonBindViewHolder методе или в файле макета XML), что, вероятно, обрезает некоторые из TextView пунктов, также при установке android:layout_width в "wrap_content", на самом деле вы игнорируете layout_weight.

Так редактировать файл макет, как это:

  ... 
      <ImageView 
      android:id="@+id/_photo" 
      android:layout_width="0dp" 
      android:layout_gravity="center_vertical" 
      android:layout_height="wrap_content" 
      android:layout_weight="0.25" /> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      ... 
+0

Спасибо за ваш ответ - это была именно ошибка! – Christian

0

Вы используете RecyclerView с вертикальной ориентацией (в Java коде)

В активности XML вы настраиваете высоту макета в Wrap_Content

компоновка карты также имеет высоту match_parent

Они не будут работать так, я потерял три дня на этом

попытаться дать высоту починки на ваш макет карты, т Эст также другие изменения другого макета, он будет работать для вас

Успехов

0

Просто попробуйте после добавления этой строки внутри recyclerview:

app:layout_behavior="@string/appbar_scrolling_view_behavior" 

так:

<android.support.v7.widget.RecyclerView 
    android:id="@+id/rv" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior"> 
</android.support.v7.widget.RecyclerView> 

Надеется, что это поможет ,