2015-08-18 35 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'已经保护了访问权限)。但是,如何在显示之前确定一件物品的高度? –

相关问题