RecyclerView 内容包裹 根据其内容而填充大小,网上各种奇葩方案 要么重写layoutManager 反复测量child 要么丢失divider 要么性能低下
在这里给出google 官方的解决方案 是在support lib>23.2.0
compile 'com.android.support:recyclerview-v7:23.2.0'
最关键的一句:
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setAutoMeasureEnabled(true);
源码:
* @param enabled <code>True</code> if the Layout should be measured by the
* RecyclerView, <code>false</code> if the LayoutManager wants
* to measure itself.
*
* @see #setMeasuredDimension(Rect, int, int)
* @see #isAutoMeasureEnabled()
*/
public void setAutoMeasureEnabled(boolean enabled) {
mAutoMeasure = enabled;
}
例子:
activity_test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/rv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#6cf">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
activity
package gitosctest.gitosc_studyproject;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* @author xuanyouwu
* @email [email protected]
* @time 2016-03-24 12:30
*/
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setAutoMeasureEnabled(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(new MyAdapter());
}
class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder> {
class MyHolder extends RecyclerView.ViewHolder {
TextView textView;
public MyHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.textView);
}
}
@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_string, parent, false);
return new MyHolder(v);
}
@Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.textView.setText("item:" + position);
}
@Override
public int getItemCount() {
return 3;
}
}
}
效果图:
当recyclerView 嵌套在scrollView 中依旧可以展现出wrap_content
如: