我正在尝试在导航栏中创建一个recyclelerview,其标题显示了个人资料信息。我希望标题高度高于其他行元素。下面是我的标题布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@color/green"
android:orientation="vertical"
android:weightSum="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:orientation="vertical"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:textColor="#ffffff"
android:text="XXXXX"
android:textSize="32sp"
android:textStyle="bold"
/>
</LinearLayout>
</RelativeLayout>
当我将其设置为回收者视图的标题时,200dp高度未在UI中反映
RecyclerView.Adapter<NavDrawerListViewHolder> adapter = new NavDrawerListAdapter(this,TITLES,this);
navList.setAdapter(adapter);
以下是recyclerview的适配器:
public class NavDrawerListAdapter extends RecyclerView.Adapter<NavDrawerListViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
Context mContext;
String[] mCharacterList;
IListItemClickListener mListener;
int holderViewType=0;
public NavDrawerListAdapter(Context context, String[] characters, IListItemClickListener clickListener) {
mContext = context;
mCharacterList = characters;
mListener = clickListener;
}
@Override
public NavDrawerListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
NavDrawerListViewHolder viewHolder;
holderViewType = viewType;
if(viewType == TYPE_HEADER) {
View v = LayoutInflater.from(mContext).inflate(R.layout.header,null);
viewHolder = new NavDrawerListViewHolder(v,TYPE_HEADER,mListener);
} else {
View v = LayoutInflater.from(mContext).inflate(R.layout.nav_item_row,null);
viewHolder = new NavDrawerListViewHolder(v,TYPE_ITEM,mListener);
}
return viewHolder;
}
@Override
public void onBindViewHolder(NavDrawerListViewHolder holder, int position) {
if(holderViewType == TYPE_HEADER) {
Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), "Roboto-Thin.ttf");
holder.name.setTypeface(typeface);
} else {
holder.characterName.setText(mCharacterList[position - 1]);
}
}
@Override
public int getItemViewType(int position) {
if (position == 0) {
return TYPE_HEADER;
}
return TYPE_ITEM;
}
@Override
public int getItemCount() {
return mCharacterList.length + 1;
}
答案 0 :(得分:14)
替换:
LayoutInflater.from(mContext).inflate(R.layout.header,null);
使用:
LayoutInflater.from(mContext).inflate(R.layout.header, parent, false);
和所有其他inflate()
来电相同。如果您知道要扩充的布局的父容器,请始终将其提供给inflate()
调用。特别是,RelativeLayout
需要这个,如果它是布局膨胀的根视图。
另外,请考虑在getLayoutInflater()
而不是Activity
上使用LayoutInflater.from()
。如果您将Activity
传递给from()
,可能会获得相同的结果。但是,一般情况下,您始终希望使用了解LayoutInflater
及其主题的Activity
,以便获得正确的结果。