android studio实现一个简易横向滑动页面
时间: 2023-10-17 09:04:32 浏览: 131
一个基于android studio实现简易计算器
首先,在布局文件中定义一个水平滑动的RecyclerView:
```
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" />
```
然后,在Activity中设置RecyclerView的LayoutManager为LinearLayoutManager,并设置其方向为水平:
```
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
```
接下来,创建一个适配器并设置给RecyclerView:
```
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<Integer> mData;
public MyAdapter(List<Integer> data) {
mData = data;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.bindData(mData.get(position));
}
@Override
public int getItemCount() {
return mData.size();
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView mTextView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.text_view);
}
public void bindData(int data) {
mTextView.setText(String.valueOf(data));
}
}
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
List<Integer> data = new ArrayList<>();
for (int i = 0; i < 10; i++) {
data.add(i);
}
MyAdapter adapter = new MyAdapter(data);
recyclerView.setAdapter(adapter);
```
最后,在item_layout布局文件中定义一个TextView用于显示数据:
```
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp" />
```
这样就实现了一个简易的横向滑动页面。
阅读全文