RecyclerView 瀑布流显示图片

该博客介绍了如何在Android中使用RecyclerView结合StaggeredGridLayoutManager实现瀑布流效果,通过加载网络图片并设置随机高度来展示新闻标题和图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="app.com.recyclerview.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>
</RelativeLayout>



item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/te1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="title" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/img1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher" />


    </LinearLayout>
</LinearLayout>



MainActivity.java
package app.com.recyclerview;

import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {
    RecyclerView rv;
    private Gson gson;
    private List<bean.ResultBean.DataBean> list;
    String path = "http://v.juhe.cn/toutiao/index?type=top&key=597b4f9dcb50e051fd725a9ec54d6653";
    private int itemWidth ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rv = (RecyclerView) findViewById(R.id.rv);

        //线性布局   VERTICAL:垂直排列     false:倒序显示
        // rv.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));

        //瀑布流显示     3:列数     HORIZONTAL:水平排列
        rv.setLayoutManager(new StaggeredGridLayoutManager(3, LinearLayout.VERTICAL));
        gson = new Gson();

        new My().execute("");

    }

    class My extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... strings) {
            String string = "";
            try {
                URL url = new URL(path);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                int code = con.getResponseCode();
                if (code == 200) {
                    InputStream is = con.getInputStream();
                    byte[] b = new byte[1024];
                    int length = 0;
                    while ((length = is.read(b)) != -1) {
                        String str = new String(b, 0, length);
                        string += str;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return string;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            bean fromJson = gson.fromJson(s, bean.class);
            list = fromJson.getResult().getData();

            MyAdapter adapter = new MyAdapter();
            rv.setAdapter(adapter);

        }
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            //每一个布局的宽度
            WindowManager wm = (WindowManager) MainActivity.this
                    .getSystemService(Context.WINDOW_SERVICE);
            int width = wm.getDefaultDisplay().getWidth();
            itemWidth = width / 3 ;


            MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
                    MainActivity.this).inflate(R.layout.item, parent,
                    false));
            return holder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, final int position) {
            holder.te1.setText(list.get(position).getTitle());

            ViewGroup.LayoutParams params =  holder.img1.getLayoutParams() ;

            int itemHeight = 300 ;

            itemHeight = new Random().nextInt(500);
            if(itemHeight < 300){
                itemHeight = 300 ;
            }

            params.width = itemWidth ;
            params.height = itemHeight ;

            holder.img1.setLayoutParams(params);
            holder.img1.setImageResource(R.mipmap.ic_launcher);

            holder.img1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(listener != null){
                        listener.onClick(view,position);
                    }
                }
            });



            holder.img1.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    listener.longClick(view,position);
                    return false;
                }
            });
//            String s = list.get(position).getThumbnail_pic_s();
//            ImageLoader.getInstance();
            ImageLoader.getInstance().displayImage(list.get(position).getThumbnail_pic_s(),holder.img1);

        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        public class MyViewHolder extends RecyclerView.ViewHolder {

            TextView te1;
            ImageView img1;

            public MyViewHolder(View itemView) {
                super(itemView);

                te1 = itemView.findViewById(R.id.te1);
                img1 = itemView.findViewById(R.id.img1);

            }
        }
    }
    static class ImageViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.img1)
        ImageView itemImageview;

        @BindView(R.id.te1)
        TextView textView;
        public ImageViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

//            itemImageview = itemView.findViewById(R.id.item_imageview);

        }

    }


    private Listener listener ;
    public void setIListener(Listener listener){
        this.listener = listener;
    }

    public interface  Listener {
        public void onClick(View view, int position);
        public void longClick(View view, int position);
    }

}

App.java

package app.com.recyclerview;

import android.app.Application;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

/**
 * Created by lenovo on 2017/11/09.
 */
public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoaderConfiguration aDefault = ImageLoaderConfiguration.createDefault(getApplicationContext());
        ImageLoader.getInstance().init(aDefault);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值