我想根据我的JSON响应更改图像

时间:2018-06-04 05:53:32

标签: android json api weather-api openweathermap

这是该应用程序的屏幕截图,我正在使用开放天气地图API制作天气应用程序,如果响应是晴朗的,我想从我的drawable文件夹中显示晴朗的天气图像。我也搜索了这个问题,但没有找到答案。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

<强> 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

如有任何问题请发表评论。