RecycleView網路請求 瀑布流
1,導依賴
implementation ‘com.android.support:recyclerview-v7:28.0.0’
2,佈局檔案
<android.support.v7.widget.RecyclerView
android:id="@+id/recy"
android:layout_width=“match_parent”
android:layout_height=“match_parent”>
</android.support.v7.widget.RecyclerView>
3,MainActivity
public class MainActivity extends AppCompatActivity {
private RecyclerView recy; private String murl="http://api.expoon.com/AppNews/getNewsList/type/1/p/1"; private TextView tv; private List<result.DataBean> data=new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recy = findViewById(R.id.recy); asyncSend(); MyAdapter adapter=new MyAdapter(data,MainActivity.this); recy.setAdapter(adapter); StaggeredGridLayoutManager staggeredGridLayoutManager=new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL); recy.setLayoutManager(staggeredGridLayoutManager); recy.setItemAnimator(new DefaultItemAnimator()); }
private void asyncSend() {
OkHttpClient okHttpClient=new OkHttpClient();
final Request request=new Request.Builder().url(murl).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(MainActivity.this,“錯誤”,Toast.LENGTH_LONG).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String string = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Gson gson=new Gson();
result result = gson.fromJson(string, result.class);
data.addAll(result.getData());
}
});
}
});
}
4,介面卡
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<result.DataBean> data;
private Context context;
public MyAdapter(List<result.DataBean> data, Context context) {
this.data = data;
this.context = context;
}
@NonNull
@Override
public MyAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view=LayoutInflater.from(context).inflate(R.layout.recy_item,viewGroup,false);
ViewHolder holder=new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull MyAdapter.ViewHolder viewHolder, int i) {
result.DataBean dataBean = data.get(i);
ViewGroup.LayoutParams layoutParams = viewHolder.itemView.getLayoutParams();
Random random=new Random();
int height=random.nextInt(300)+300;
layoutParams.height=height;
viewHolder.itemView.setLayoutParams(layoutParams);
Glide.with(context).load(data.get(i).getPic_url()).into(viewHolder.img);
}
@Override
public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final ImageView img;
public ViewHolder(@NonNull View itemView) {
super(itemView);
img = itemView.findViewById(R.id.img);
}
}
}