今天來學習下一個RecyclerView控件
首先先來配置下
<code>
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.0.0-beta1'
compile 'com.android.support:recyclerview-v7:24.+'
}
</code>
接下來做一個橫向的例子
xml文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tony.uiapplication.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
java文件
public class MainActivity extends AppCompatActivity {
private RecyclerView mVRecycler;
private Adapter mAdapter;
private List<String> mList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVRecycler = (RecyclerView) findViewById(R.id.recyclerview);
mVRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
mList = new ArrayList<>();
for (int i = 1; i < 17; i++) {
mList.add("text" + i);
}
mAdapter = new Adapter(this, mList);
mVRecycler.setAdapter(mAdapter);
}
class Adapter extends RecyclerView.Adapter<MainActivity.ViewHolder> {
private Context context;
private List<String> list;
public Adapter(Context context, List<String> list) {
this.context = context;
this.list = list;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_recycler, parent, false));
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.vText.setText(list.get(position));
}
@Override
public int getItemCount() {
return list == null ? 0 : list.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
// ImageView vImage;
TextView vText;
public ViewHolder(View itemView) {
super(itemView);
// vImage = (ImageView) itemView.findViewById(R.id.img);
vText = (TextView) itemView.findViewById(R.id.text);
}
}
}
下面是效果圖