Android RecyclerView添加Header头部
Android RecyclerView添加Header头部
Android RecyclerView不像以前的ListView那样直接添加头部,如果要给RecyclerView增加头部,则需要自己写或者使用第三方开源项目。
RecyclerViewHeader是github上的一个开源项目,旨在为Android RecyclerView增加头部,其在github上的项目主页是:https://github.com/blipinsk/RecyclerViewHeader
RecyclerViewHeader使用相对比较简单,写一个例子。
注意RecyclerViewHeader的布局文件写法:
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> <com.bartoszlipinski.recyclerviewheader2.RecyclerViewHeader xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/header" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="top"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/holo_orange_light" android:gravity="center" android:text="zhang phil @ csdn" android:textColor="@android:color/white" /> </com.bartoszlipinski.recyclerviewheader2.RecyclerViewHeader> </FrameLayout>
上层Java代码:
package zhangphil.app; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.bartoszlipinski.recyclerviewheader2.RecyclerViewHeader; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView); LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(layoutManager); ItemAdapter adapter = new ItemAdapter(); recyclerView.setAdapter(adapter); //添加RecyclerView头部 RecyclerViewHeader header = (RecyclerViewHeader) findViewById(R.id.header); header.attachTo(recyclerView); } private class ItemViewHolder extends RecyclerView.ViewHolder { public TextView text; public ItemViewHolder(View itemView) { super(itemView); text = (TextView) itemView.findViewById(android.R.id.text1); } } private class ItemAdapter extends RecyclerView.Adapter<ItemViewHolder> { @Override public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = View.inflate(parent.getContext(), android.R.layout.simple_list_item_1, null); ItemViewHolder holder = new ItemViewHolder(view); return holder; } @Override public void onBindViewHolder(ItemViewHolder holder, int position) { holder.text.setText(String.valueOf(position)); } @Override public int getItemCount() { return 20; } } }
代码运行结果: