RecyclerView的应用及RecyclerView的点击事件

时间秒杀一切 提交于 2019-12-02 21:33:57

第一步:导入依赖包   implementation 'com.android.support:recyclerview-v7:25.3.1'

第二步:用 JSONArray 解析后台数据并setadapter  

JSONArray jsonArray = jsonObject.getJSONArray("obj");

if (jsonArray.size() > 0) {

for (int i = 0; i < jsonArray.size(); i++) {

JSONObject jb = jsonArray.getJSONObject(i); 

patientID = jb.getInteger("id");

patientName = jb.getString("name"); 

patientPhone = jb.getString("phone");

patientSFZNum = jb.getString("identityno");

PatientPhoneBean patientPhoneBean = new PatientPhoneBean();

patientPhoneBean.setPatientID(patientID);

patientPhoneBean.setPatientName(patientName);

patientPhoneBean.setPatientPhone(patientPhone);

patientPhoneBean.setPatientSFZNum(patientSFZNum);

patientPhoneList.add(patientPhoneBean);

}

phoneBean.setPhoneobj(patientPhoneList);

Message message = Message.obtain();

message.what = GETPATIENTPHONE_FLAG;

message.obj = phoneBean.getPhoneobj();

handler.sendMessage(message);

然后在 handleMessage处理收到的消息:

case GETPATIENTPHONE_FLAG:

getPatientPhoneAdapter.addData((List<PatientPhoneBean>) msg.obj);

getPatientPhoneRV.setAdapter(getPatientPhoneAdapter);

getPatientPhoneSwipeRL.setRefreshing(false);

break;

 

第三步:在Adapter里面的操作:

@Override

public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {

if (holder instanceof GetPatientPhoneAdapter.MyHolder) {

final PatientPhoneBean data = ppData.get(position);

((GetPatientPhoneAdapter.MyHolder) holder).tv_num.setText(data.getPatientID() + "");

((GetPatientPhoneAdapter.MyHolder) holder).tv_name.setText(data.getPatientName() + "");

((GetPatientPhoneAdapter.MyHolder) holder).tv_phone.setText(data.getPatientPhone() + "");

((GetPatientPhoneAdapter.MyHolder) holder).tv_sfznum.setText(data.getPatientSFZNum() + "");

//点击事件

((GetPatientPhoneAdapter.MyHolder) holder).ll_commitphone.setOnClickListener(new View.OnClickListener(){

@Override

public void onClick(View v) {

if (listener != null) {

listener.onClick(position,data.getPatientPhone() + "");

}}});

}}

 

//RecyclerView的点击事件

//一、在recycler的适配器中定义接口

public interface OnItemClickListener {

void onClick(int position, String phone);

}

private OnItemClickListener listener;

//第二步, 写一个公共的方法

public void setOnItemClickListener(OnItemClickListener listener) {

this.listener = listener;

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!