【问题标题】:set images in image in a loop with Picasso使用毕加索循环设置图像中的图像
【发布时间】:2019-07-31 00:25:45
【问题描述】:

我有一个像这样的.json

 {
        "0": {

            "image_path": "192.168.1.52/test/image/im1.jpg",
            "title": "image 1"
        },
          "1": {

            "image_path": "192.168.1.52/test/image/im2.jpg",
            "title": "image 2"
        },
          "2": {

            "image_path": "192.168.1.52/test/image/im2.jpg",
            "title": "image 3"
        },
  "size": "3"
}

我的安卓部分是...

 RelativeLayout layout= (RelativeLayout) getView().findViewById(R.id.relLayout);
JSONObject jObj = new JSONObject(response);
int size =  Integer.parseInt(jObj.getString("size"));

   for(int i = 0; i < size; i++)
     {
              JSONObject jObj_ =  jObj.getJSONObject(""+i);
                        String image_path_variable = jObj_.getString("image_path");
      }

这就是我卡住的地方。我不知道如何使用我在.json 文件中的路径动态插入图像。 所以我的布局将有多个图像视图,具体取决于 for 循环有什么例如有 3 个图像页面将有 3 个图像 我的意思是我的 json 不会总是有 3 个图像,有时它会超过 3 个或更少,所以图像视图需要在 for 循环中创建它自己

【问题讨论】:

  • 有什么方法可以修改json 结构使其更容易解析?我的建议是拥有对象数组([ ... ])({ ... })。之后你就不需要size01... 之类的键。
  • 我更新了我的问题
  • 但是你没有回答我的问题。目前的json结构不太好。
  • @Boken 我可以,但我不确定我是否想要,因为它目前非常复杂
  • 好的,那么这个json可以有多少个元素呢?以及当文件有时布局应该如何,例如20个元素?您期待 20 个 ImageViews 吗?如果是,你应该使用RecyclerView

标签: android json android-imageview picasso


【解决方案1】:

所以,在 Kotlin 中一步一步来。

我的 json 文件(在 res &gt; raw &gt; people.json 中):

{
  "0": {
    "image_path": "https://images.unsplash.com/photo-1485199692108-c3b5069de6a0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=80",
    "title": "Girl 1"
  },
  "1": {
    "image_path": "https://images.unsplash.com/photo-1520065949650-380765513210?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=80",
    "title": "Girl 2"
  },
  "2": {
    "image_path": "https://images.unsplash.com/photo-1547513609-d80733850d2e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=80",
    "title": "Girl 3"
  },
  "3": {
    "image_path": "https://images.unsplash.com/photo-1550094195-2234fa4e2128?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1000&q=80",
    "title": "Girl 4"
  },
  "size": "4"
}

活动布局 (res &gt; layout &gt; activity_main.xml)

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

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layoutManager="android.support.v7.widget.GridLayoutManager"
        app:spanCount="2" />

</LinearLayout>

我们应用的主要活动 (MainActivity.kt)

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setupUi()
    }

    private fun setupUi() {
        // Read file content
        val jsonFile = resources
            .openRawResource(R.raw.images)
            .bufferedReader()
            .readText()

        // Change "String" in to "Json Object"
        val root = JSONObject(jsonFile)

        // Get size of the list
        val size = root.getString("size").toInt()

        // Create (empty) list of people
        val peopleList = mutableListOf<Person>()

        // Loop to read all of the people
        for (position in 0 until size) {
            val element = root.getJSONObject(position.toString())

            // Change json in to Kotlin object
            val photo = Person(
                element.getString("image_path"),
                element.getString("title")
            )

            // Add element to the list
            peopleList.add(photo)
        }

        // Add adapter for RecyclerView
        recycler_view.adapter = PeopleAdapter(this, peopleList)
    }
}

列表元素 (res &gt; layout &gt; list_item.xml)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/image_view"
        android:layout_width="100dp"
        android:layout_height="150dp"
        android:layout_margin="10dp"
        android:scaleType="centerCrop"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/title"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:background="@color/colorBlack"
        android:gravity="center"
        android:textColor="@color/colorWhite"
        app:layout_constraintBottom_toBottomOf="@id/image_view"
        app:layout_constraintEnd_toEndOf="@id/image_view"
        app:layout_constraintStart_toStartOf="@id/image_view" />

</android.support.constraint.ConstraintLayout>

表示列表中单个元素的模型类 (Person.kt)

class Person(
    val image: String,
    val title: String
)

适配器(使用ViewHolder 模式)

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.list_item.view.*

class PeopleAdapter(
    private val context: Context,
    private val listOfColor: List<Person>
) : RecyclerView.Adapter<PeopleAdapter.ViewHolder>() {

    // Creating elements (one item from list)
    override fun onCreateViewHolder(viewGroup: ViewGroup, p1: Int): ViewHolder {
        val view = LayoutInflater
            .from(viewGroup.context)
            .inflate(R.layout.list_item, viewGroup, false)

        return ViewHolder(view)
    }

    // Number of elements
    override fun getItemCount(): Int = listOfColor.size

    // Fill elements with a data
    override fun onBindViewHolder(row: ViewHolder, position: Int) {
        row.bind(position)
    }

    // Class responsible for one (single) row
    inner class ViewHolder(private val item: View) : RecyclerView.ViewHolder(item) {
        fun bind(position: Int) {
            // Get image address
            val person = listOfColor[position]

            // Load image
            Glide.with(context).load(person.image).into(item.image_view)

            // Set text
            item.title.text = person.title
        }
    }
}

记住大约三 (3) 个依赖项

implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation "com.github.bumptech.glide:glide:4.8.0"
implementation 'com.android.support.constraint:constraint-layout:1.1.3'

和(1)权限(清单)

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

颜色res &gt; values &gt; colors.xml

<color name="colorWhite">#FFF</color>

<!-- Black with 50% transparency -->
<color name="colorBlack">#80000000</color>

预期输出:

【讨论】:

  • 请接受答案或询问不清楚的事情?
【解决方案2】:

您可以将此作为参考 https://stackoverflow.com/a/10593838/7586266 这个想法是让你迭代你有 "0" 、 "1" 、 "2" ...等的 JSON 对象

为了做到这一点,就像您在此处输入大小一样进入 json 对象

jObj.getString("size")

您可以在 for 循环中使用 i 来获取包含您的网址的 jObj 像这样

JSONObject jObj =  json.getJSONObject(Integer.toString(i)); // where json is your whole json and you are getting the object "0","1" and "2" from it
string image_path_variable = jObj .getString("image_path");

您可以将 i 处的 JObj 解析为 JSONObject,您可以获得“image_path” 一旦你能够做到这一点,你就可以使用

Picasso.get().load(image_path_variable).into(your_desired_image_view);

【讨论】:

  • 我想我不是很清楚,所以我的布局将有多个图像视图,具体取决于 for 循环的示例,例如页面有 3 个图像,页面将有 3 个图像
  • @o3203823 你在使用 recyclerview 吗?或者换句话说,生成图像视图的适配器?
【解决方案3】:
RelativeLayout layout= (RelativeLayout) getView().findViewById(R.id.relLayout);
JSONObject jObj = new JSONObject(response);
int size =  Integer.parseInt(jObj.getString("size"));   

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

   JSONObject itemObj = jObj.get(Integer.valueOf(i)).getAsJsonObject();
   String path = itemObj.getString("image_path")

   ImageView view = new ImageView(context);

   RelativeLayout.LayoutParams params = new  RelativeLayout.LayoutParams(
                                    RelativeLayout.LayoutParams.WRAP_CONTENT, 
                                    RelativeLayout.LayoutParams.WRAP_CONTENT);

   params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
   params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);

   layout.addView(view, params);

   Picasso.get().load(path).into(view);
}

【讨论】:

  • 我想我不是很清楚,所以我的布局将有多个图像视图,具体取决于 for 循环的示例,例如页面有 3 个图像,页面将有 3 个图像
  • 兄弟,我很欣赏你的回答,但我认为你不理解我的问题,所以我所说的我的 json 不会总是有 3 张图像,有时它会超过 3 或更少,所以图像视图需要在 for 循环中创建它自己非常感谢
猜你喜欢
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
  • 2014-08-21
  • 1970-01-01
  • 2017-09-18
  • 2019-07-13
  • 1970-01-01
  • 2021-02-21
相关资源
最近更新 更多