学习《第一行代码》第三章笔记
项目地址:https://github.com/YuQiao0303/UIWidgetTest-LearnAndroid
总体步骤
- 添加依赖
- 实体类
- 列表子项布局文件fruit_item.xml
- 适配器
- activity中:
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
FruitAdapter adapter = new FruitAdapter(fruitList);
recyclerView.setAdapter(adapter);
- 给具体的view注册监听事件
添加依赖
打开app/build.gradle文件, 在dependencies 闭包中添加如下内容:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:recyclerview-v7:24.2.1'
testCompile 'junit:junit:4.12'
}
添加完之后记得要点击一下Sync Now来进行同步。
我个人加完是这样:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:percent:28.0.0' //百分比库的依赖
implementation 'com.android.support:recyclerview-v7:28.0.0' //RecyclerView 的依赖
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
鼠标单击事件
在ViewHolder 中添加了变量来保存子项最外层布局的实例,
然后在onCreateViewHolder() 方法中注册点击事件就可以了。
RecyclerView可以轻松实现子项中任意控件或布局的点击事件。
我们在两个点击事件中先获取了用户点击的position, 然后通过position拿到相应的Fruit 实例, 再使用Toast分别弹出两种不同的内容以示区别。
/**
* 给ViewHolder的属性赋值(设置ViewHolder对应的布局文件:fruit_item.xml)
* 注册鼠标单击事件
* @param parent
* @param viewType
* @return
*/
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//给ViewHolder的属性赋值
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.
fruit_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
//整个列表子项的鼠标单击事件
holder.fruitView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
Fruit fruit = mFruitList.get(position);
Toast.makeText(v.getContext(), "you clicked view " + fruit.getName(),
Toast.LENGTH_SHORT).show();
}
});
//列表子项中imageView的鼠标单击事件
holder.fruitImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
Fruit fruit = mFruitList.get(position);
Toast.makeText(v.getContext(), "you clicked image " + fruit.getName(),
Toast.LENGTH_SHORT).show();
}
});
return holder;
}
网友评论