Android:如何动态地在列表中设置ImageView src

时间:2015-02-16 15:02:01

标签: java android json android-studio imageview

我是android新手,我有新闻website 我正在开发一个Android应用程序,主要活动从this link捕获一个JSON节点并显示ListView中的所有文章, 列表中的每个项目都有一个图像,标题和这篇特定文章的预告片。

现在我已经为标题和描述编写了一个java代码,一切都运行得很好,但我也想显示图像,我不知道该怎么做。

这是我的MainActivity.java:

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;



public class MainActivity extends ListActivity {

    //Create a progress dialog instance
    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "http://www.ana.fm/api/main/";

    // JSON Node names
    private static final String TAG_ARTICLES = "articles";
    private static final String TAG_ID = "id";
    private static final String TAG_TITLE = "title";
    private static final String TAG_TEASER = "teaser";
    private static final String TAG_COVER_PHOTO = "cover_photo";

    // contacts JSONArray
    JSONArray articles = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

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

        contactList = new ArrayList<HashMap<String, String>>();

        ListView lv = getListView();

        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String article_id = ((TextView) view.findViewById(R.id.article_id))
                        .getText().toString();
                // Starting single contact activity
                Intent in = new Intent(getApplicationContext(),
                        SingleContactActivity.class);
                in.putExtra(TAG_ID, article_id);
                startActivity(in);

            }
        });

        // Calling async task to get json
        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }
        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    articles = jsonObj.getJSONArray(TAG_ARTICLES);

                    // looping through All Contacts
                    for (int i = 0; i < articles.length(); i++) {
                        JSONObject c = articles.getJSONObject(i);

                        String id = c.getString(TAG_ID);
                        String title = c.getString(TAG_TITLE);
                        title = Html.fromHtml(title).toString();
                        String teaser = c.getString(TAG_TEASER);
                        teaser = Html.fromHtml(teaser).toString();
                        String cover_photo = "http://www.ana.fm/med_photos/articles/";
                        cover_photo = cover_photo.concat(c.getString(TAG_COVER_PHOTO));



                        // tmp hashmap for single contact
                        HashMap<String, String> article = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        article.put(TAG_ID, id);
                        article.put(TAG_TITLE, title);
                        article.put(TAG_TEASER, teaser);
                        article.put(TAG_COVER_PHOTO, cover_photo);


                        // adding contact to contact list
                        contactList.add(article);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
                new GetContacts().execute();
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item, new String[] { TAG_ID, TAG_TITLE, TAG_TEASER, TAG_COVER_PHOTO}, new int[] { R.id.article_id,  R.id.title,
                    R.id.teaser, R.id.cover_photo});
            setListAdapter(adapter);
        }
    }
}

这里是activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@color/white">
    <!-- Main ListView 
         Always give id value as list(@android:id/list)
    -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:divider="@android:color/transparent"
        android:dividerHeight="10.0sp"
        />

</LinearLayout>

这里是list_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="wrap_content"
    android:orientation="vertical"
    android:padding="10dp"
    android:layout_marginBottom="20dp"
    android:background="@color/light_grey">


    <!-- Cover photo -->
    <ImageView
        android:id="@+id/cover_photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

    <!-- ID Label -->
    <TextView
        android:id="@+id/article_id"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" />
    <!-- Title Label -->
    <TextView
        android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dip"
        android:paddingTop="6dip"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:textStyle="bold" />

    <!-- Teaser label -->
    <TextView
        android:id="@+id/teaser"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="@color/medium_grey" />



</LinearLayout>

任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:0)

根据您的JSON,您拥有的只是图像文件名。即:

{
.
.
.
"cover_photo":"2018061675.jpg"
}   

您首先需要一个API来从您的图像传递InputStream。 之后你有3个选择:

  1. <强> Volley

    • 它是一个非常简单易用(但非常强大)的库,它可以帮助您维护资源池和内存。
    • This视频是对凌空的介绍。请注意,如果您之前有过Android体验,或者我建议您只是了解它如何影响您的常规方法。
    • android tutorial for volley
    • 中提到了提出图片请求
  2. OkHttp

    • 它需要更多工作,并且对于整体http请求使用而言是轻量级的。
    • 图像请求可以作为detailed here
    • 文件获取
  3. Picasso

    • 简单库仅用于图像请求目的
  4. 手动执行

    • 使用输入流并手动获取并构建图像
    • This就是一个很好的例子。