2015-08-18 201 views
0

我的佈局是這樣的:設置RecyclerView高度匹配的內容

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_height="match_parent" android:layout_width="fill_parent"> 
<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 
    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 
     <TextView 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="Latest News:" 
      android:textAppearance="?android:attr/textAppearanceLarge" 
      android:textSize="35sp" /> 
     <android.support.v7.widget.RecyclerView 
       android:id="@+id/news" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content"/> 
    </LinearLayout> 
    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 
     <TextView 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:paddingTop="20dip" 
       android:text="Something else" 
       android:textAppearance="?android:attr/textAppearanceLarge" 
       android:textSize="35sp" /> 
     <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="foo bar..." 
       android:textAppearance="?android:attr/textAppearanceMedium" /> 
    </LinearLayout> 
</LinearLayout> 
</ScrollView> 

我將項目添加到RecyclerView這樣的:

 // download the feed... 
     RecyclerView rv = (RecyclerView) v.findViewById(R.id.news); 
     rv.setLayoutManager(new LinearLayoutManager(getActivity())); 
     rv.setAdapter(new NewsAdapter(feed.getItems())); 

現在我期待的RecyclerView自動調整自身相匹配裏面的物品的長度。但是,這不會發生,而不是停留RecyclerView「隱形」(例如,具有零高度):

There should be news

我怎麼能動態調整RecyclerView的高度相匹配的高度,它的內容?

+1

你不能!這是Android上衆所周知的限制。它不能很好地處理嵌套滾動。所以你不能在ScrollView裏面有一個RecyclerView。 – Budius

回答

-1

您可以使用這樣的代碼:

rv.post(new Runnable() { 
    @Override 
    public void run() { 
     final int newHeight = // number of items * one item height in px 
     ViewGroup.LayoutParams params = rv.getLayoutParams(); 

     if (params == null) { 
      params = ((ViewGroup)rv.getParent()).generateDefaultLayoutParams(); 
      params.width = ViewGroup.LayoutParams.MATCH_PARENT; 
     } 

     params.height = newHeight; 
     rv.setLayoutParams(params); 
    } 
} 

您可以使用這一招:

View view = getLayoutInflater().inflate(R.layout.*your_item_id*, null, false); 
ItemViewHolder holder = new ItemViewHolder(view); 
//set data to this holder, same code as onBindViewHolder(...) 

view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.AT_MOST); 
int itemHeight = view.getMeasuredHeight(); 
+0

是的,這可以工作(但'generateDefaultLayoutParams'已經保護了訪問權限)。但是,如何在顯示之前確定一件物品的高度? –

相關問題