Recyclerview
一 简介:
Recyclerview是谷歌公司推出了一个用于大量数据展示的新控件,用于替代listview,给用户带来极大的方便性与灵活性。
二 使用方法:
1.导入Recyclerview依赖( implementation 'com.android.support:recyclerview-v7:28.0.0')
2.编写布局以及itemView布局
main.xml
<android.support.v7.widget.RecyclerView android:layout_height="match_parent" android:layout_width="match_parent" android:id="@+id/review"/>
itemView布局
<ImageView android:layout_height="150dp" android:layout_width="150dp" android:sr`在这里插入代码片`c="@mipmap/ic_launcher" android:id="@+id/img_iv"/>
<LinearLayout android:layout_height="80dp" android:layout_width="150dp" android:layout_alignBottom="@+id/img_iv" android:orientation="vertical" android:alpha="0.5" android:background="#000">
<TextView android:layout_height="50dp" android:layout_width="match_parent" android:id="@+id/text01"/>
<TextView android:layout_height="50dp" android:layout_width="match_parent" android:id="@+id/text02"/>
</LinearLayout>
3.生成RecyclerView数据源(生成Bean类略)
public class Mysynctask extends AsyncTask<String,Void,String>{
String str = "http://mrobot.pcauto.com.cn/v2/cms/channels/3?pageNo=1&pageSize=20&v=4.0.0";
StringBuffer sbf = new StringBuffer();
List<Bean.DataBean> data;
private Myadapter myadapter;
private RecyclerView recyclerView;
public Mysynctask(String str,List<Bean.DataBean> data, Myadapter myadapter, RecyclerView recyclerView) {
this.str = str;
this.data = data;
this.myadapter = myadapter;
this.recyclerView = recyclerView;
}
@Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(str);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(1000*30);
con.setReadTimeout(1000*60);
con.setRequestMethod("GET");
if(con.getResponseCode() == 200) {
InputStream is = con.getInputStream();
byte[] bys = new byte[1024];
int len = 0;
while((len = is.read(bys))!=-1) {
sbf.append(new String(bys,0,len));
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sbf.toString();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Gson gson = new Gson();
Bean bean = gson.fromJson(s, Bean.class);
data = bean.getData();
myadapter = new Myadapter();
recyclerView.setAdapter(myadapter);
myadapter.refresh(data);
}
}
4.编写RecyclerView适配器
public class Myadapter extends RecyclerView.Adapter<Myadapter.ViewHolder>{
List<Bean.DataBean> data = new ArrayList<>();
private Context context;