Android studio相关(4):B站‘Android架构解析’基础入门笔记——第四章RecyclerView
1、RecyclerView
·
学习B站‘Android架构解析’【2021最新版】Android(安卓)开发零基础入门课程【全套】
(自学还是要尽量跟着视频敲一敲代码,做做笔记------如有侵权,联系我删除)
文章目录
1、RecyclerView
MainActivity.java
package com.example.myrecyclerview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<Bean> data = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0;i <100 ;i ++){
Bean bean = new Bean();
bean.setName("享学"+i);
data.add(bean);
}
RecyclerView recyclerview = findViewById(R.id.tv);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerview.setLayoutManager(linearLayoutManager);
MyAdapter myAdapter = new MyAdapter(data, this);
recyclerview.setAdapter(myAdapter);
}
}
Myadapter.java
package com.example.myrecyclerview;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<Bean> data;
private Context context;
public MyAdapter(List<Bean> data, Context context) {
this.data = data;
this.context = context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = View.inflate(context,R.layout.recyclerview_item,null);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.tv.setText(data.get(position).getName());
}
@Override
public int getItemCount() {
return data == null ? 0:data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
private TextView tv;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
tv = itemView.findViewById(R.id.tv);
}
}
}
更多推荐
已为社区贡献2条内容
所有评论(0)