准备工作:打开项目的build.gradle 添加对support V7的引用 代码如下
dependencies { ... compile 'com.android.support:appcompat-v7:21.0.3' ... }
.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/recyclerView" android:scrollbars="vertical" android:layout_hljs-string" >"match_parent" android:layout_hljs-string" >"match_parent" />
此处的RecyclerView 是纵向的
public class MainActivity extends Activity { private RecyclerView mRecyclerView; private ItemAdapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; private ArrayList items = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView); //列数为两列 int spanCount = 2; mLayoutManager = new StaggeredGridLayoutManager( spanCount, StaggeredGridLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(mLayoutManager); //构建一个临时数据源 for (int i = 0; i <100; i++) { items.add("i:" + i); } mAdapter = new ItemAdapter(items); mRecyclerView.setAdapter(mAdapter); } }
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.viewHolder> { private ArrayList items = new ArrayList<>(); public ItemAdapter(ArrayList items) { this.items = items; } @Override public viewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_card, viewGroup, false); return new viewHolder(view); } @Override public int getItemViewType(int position) { return super.getItemViewType(position); } @Override public void onBindViewHolder(viewHolder viewHolder, int position) { String info = items.get(position); View view = viewHolder.itemView; TextView textView = (TextView) view.findViewById(R.id.info_text); textView.setText(info); //手动更改高度,不同位置的高度有所不同 textView.setHeight(100 + (position % 3) * 30); } @Override public int getItemCount() { return items.size(); } class viewHolder extends RecyclerView.ViewHolder { public viewHolder(View itemView) { super(itemView); } } }
"http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_hljs-string" >"fill_parent" android:gravity="center" android:layout_hljs-string" >"fill_parent"> .support.v7.widget.CardView android:id="@+id/card_view" android:layout_gravity="center" android:layout_hljs-string" >"150dp" android:layout_hljs-string" >"wrap_content" card_view:cardUseCompatPadding="true" card_view:cardCornerRadius="4dp"> "@+id/info_text" android:layout_hljs-string" >"fill_parent" android:gravity="center" android:layout_hljs-string" >"wrap_content" /> .support.v7.widget.CardView>
此处使用了CardView,如想正确调用到CardView,在build.gradle中添加对cardview的引用代码如下
dependencies { ... compile 'com.android.support:cardview-v7:21.0.3' ... }