【问题标题】:I want to change the image based on my JSON response我想根据我的 JSON 响应更改图像
【发布时间】:2018-06-04 05:53:31
【问题描述】:

这是应用程序的屏幕截图,我正在使用 open-weather-map API 制作天气应用程序,如果响应是晴天,我想从我的可绘制文件夹中显示晴天天气图像。我也搜索过这个问题,但没有找到答案。

【问题讨论】:

  • 我认为您需要某种基于 json 响应字符串的静态映射来显示基于它的图像。
  • 得到json响应后,使用switch case,根据响应更新图片。

标签: android json api weather-api openweathermap


【解决方案1】:
imageview= (ImageView)findViewById(R.id.imageView);   

String request=new StringRequest(Request.Method.GET, url, new 
Response.Listener<String>() 
{
        @Override
        public void onResponse(String response)
        {

            try {

                JSONObject jsonObject = new JSONObject(response);

                JSONArray jsonArray =jsonObject.getJSONArray("users");

                String re = "";

                wlist=new ArrayList<>();

                for (int i = 0; i < jsonArray.length(); i++) 
                {
                        JSONObject jsonObject1 =jsonArray.getJSONObject(i);

                        re = jsonObject1.getString("re");

                        if(re.equals("sunny")
                        {
                           imageview.setImageDrawable(getResources().getDrawable(R.drawable.sunnyImage);

                        }

                        Model m = new Model(re);
                        userlist.add(user);
                }

                // Initialize adapter
                wlist.setAdapter(yourAdapter);
                //set adapter on your view

【讨论】:

    【解决方案2】:

    You can try this function:-

    private Drawable getDrawable(String source)
        {
            Drawable drawable;
            int sourceId =
                    getApplicationContext()
                            .getResources()
                            .getIdentifier(source, "drawable", getPackageName());
    
            drawable = getApplicationContext().getResources().getDrawable(dourceId);
    
            drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
    
            return drawable;
        }
    

    function implementation:-

    /*If you can get the JSON response same as the name of the image or set the name of the image as per your response this will work very efficiently*/
    
     imageView.setImageDrawable(getDrawable("sunny"));//this will return a drawable whose name is sunny
    

    如有问题请评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2019-05-20
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多