今天在学习RecyclerView时,发现了一个问题,当我将RecyclerView嵌套在ScrollView中,为了防止点击冲突,对线性RecyclerView设置了setNestedScrollingEnable(false),此方法是防止ScrollView和RecyclerView的点滑动冲突,由于线性RecyclerView包含有多条记录,而此时只显示部分记录,很明显显示不完全。
为了解决此问题,对线性RecyclerView进行高度定义:
1.直接定义RecyclerView的高度
前提:已知RecyclerView的记录的条数
具体操作:直接在布局文件中把RecyclerView的高度定义上
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_list"
android:layout_width="match_parent"
android:layout_height="300dp">
</android.support.v7.widget.RecyclerView>
2.手动计算RecyclerView的高度
前提:不知道RecyclerView的记录的条数
具体操作:
(1)计算ItemView的高度
(2)计算ItemView的数量
(3)ItemViewHeight * ItemViewNum = RecyclerViewHeight
具体代码:
package com.musicplaer.eminemmusic.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.musicplaer.eminemmusic.R;
public class MusicLinearAdapter extends RecyclerView.Adapter<MusicLinearAdapter.ViewHolder> {
private Context context;
private View mItemView;
private RecyclerView mRv;
private boolean isCalHeight = false;
public MusicLinearAdapter(Context context , RecyclerView mRv){
this.context = context;
this.mRv = mRv;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
mItemView = LayoutInflater.from(context).inflate(R.layout.item_list_music,viewGroup,false);
return new ViewHolder(mItemView);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
setRecyclerViewHeight();
}
@Override
public int getItemCount() {
return 8;
}
/**
* 手动计算RecyclerView的高度
* 步骤:
* 1.获取ItemView的高度
* 2.ItemView的数量
* 3.两者相乘得出RecyclerView的高度
*/
private void setRecyclerViewHeight(){
//避免多次计算
if(isCalHeight){
return;
}
isCalHeight = true;
//获取ItemView的高度
RecyclerView.LayoutParams itemview_layoutParams = (RecyclerView.LayoutParams)mItemView.getLayoutParams();
//获取ItemView的数量
int itemCount = getItemCount();
//两者相乘得出RecyclerView的高度
int recyclerViewHeight = itemCount * itemview_layoutParams.height;
//设置RecyclerView的高度
LinearLayout.LayoutParams rvmview_ayoutParams = (LinearLayout.LayoutParams) mRv.getLayoutParams();
rvmview_ayoutParams.height = recyclerViewHeight;
mRv.setLayoutParams(rvmview_ayoutParams);
}
class ViewHolder extends RecyclerView.ViewHolder{
public ViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}