Android瀑布流

以下是一个简单的示例代码,演示如何在Android Studio中解析指定网页的图片URL,并展示在错乱瀑布流布局中:

1. 添加网络权限:在项目的AndroidManifest.xml文件中添加以下权限:

<uses-permission android:name="android.permission.INTERNET" />

2. 创建一个新的Activity,并在XML布局文件中添加一个RecyclerView组件:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

3. 创建一个数据模型类ImageModel来存储图片URL:

public class ImageModel {
    private String imageUrl;

    public ImageModel(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public String getImageUrl() {
        return imageUrl;
    }
}

4. 创建一个适配器类ImageAdapter来加载图片URL并展示在瀑布流布局中:

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
    private List<ImageModel> imageList;
    private Context context;

    public ImageAdapter(List<ImageModel> imageList, Context context) {
        this.imageList = imageList;
        this.context = context;
    }

    @NonNull
    @Override
    public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_image, parent, false);
        return new ImageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
        ImageModel imageModel = imageList.get(position);
        String imageUrl = imageModel.getImageUrl();

        Glide.with(context)
                .load(imageUrl)
                .centerCrop()
                .into(holder.imageView);
    }

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

    public class ImageViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;

        public ImageViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageView);
        }
    }
}

5. 在Activity中发起HTTP请求,并解析返回的数据:

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private ImageAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

        List<ImageModel> imageList = new ArrayList<>();
        adapter = new ImageAdapter(imageList, this);
        recyclerView.setAdapter(adapter);

        // 发起HTTP请求并解析数据
        new ParseDataTask().execute();
    }

    private class ParseDataTask extends AsyncTask<Void, Void, List<ImageModel>> {
        @Override
        protected List<ImageModel> doInBackground(Void... voids) {
            List<ImageModel> imageList = new ArrayList<>();
            try {
                Document document = J

你可能感兴趣的:(android)