Android的:如何设置ImageView的SRC在列表中动态 [英] Android: How to set the ImageView src in a list dynamically

查看:220
本文介绍了Android的:如何设置ImageView的SRC在列表中动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新到Android,我有一个消息网站
和我开发一个Android应用程序,主要活动从捕获的在ListView此链接并显示所有文章,
列表中的每个项目都有一个图像,标题和这种特殊商品的难题。

I'm new to android, i have a news website and i'm developing an android app, the main activity catches a JSON node from this link and displays all the articles in a ListView, each item in the list has an image, title and a teaser of this particular article.

现在我已经写了一个java code的标题和说明,一切都可以正常使用,但我想也显示图像,我不知道该怎么做。

now i have written a java code for the title and the description and everything is working perfectly, but i want to display the images too and i don't know how to do that.

下面是我的MainActivity.java:

Here's my 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中:

And here's the 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:

And here's the 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>

任何人都可以帮忙吗?

Anyone can help ?

推荐答案

因此​​,这里是如何实现自定义适配器。

So here is how to implement a custom adapter.

在这个例子中,我们有一个包含名称姓Properties对象图片网址(网页为图片拍摄地点)

For this example we have a person object containing properties for name, surname and imageUrl (the web location for the image)

下面是Person类对象:

The following is the Person Class Object:

public class Person {

    String name;
    String surname;
    String imageUrl;

    public Person() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }
}

现在我们创建一个XML布局,将填充我们的列表视图数据。没有什么花哨这里只是包含的TextView name的布局,另一个姓,为我们的图像的ImageView的。在这种情况下,该文件被称为person_cell.xml

Now we create an xml layout which will populate our listview with data. Nothing fancy here just a layout containing a textview for name, another for surname and an imageview for our image. The file in this case is called person_cell.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="match_parent"
android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/person_cell_txtName" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/person_cell_txtSurname" />

     <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/person_cell_imageview" />
</LinearLayout>

所以,直到现在,我们有我们的人对象的类,和一个XML布局准备使用。现在,我们建立我们的自定义适配器。创建一个名为类 MyAdapter 延伸 ArrayAdapter 类型 。需要注意的是,我们需要上下文传递给适配器,因为我们将使用毕加索加载图像。

So til now we have a class for our person object, and an xml layout ready for use. Now we build our Custom Adapter. Create a class named MyAdapter which extends ArrayAdapter of type Person. Note that we need to pass the context to the adapter since we will be using Picasso to load the image.

public class MyAdapter extends ArrayAdapter<Person> {

    Context context;
    List<Person>myList;

    public MyAdapter(Context context, int resource, List<Person> objects) {
        super(context, resource, objects);

        this.context = context;
        this.myList = objects;
    }


    @Override
    public int getCount() {
        if(myList != null)
            return myList.size();
        return 0;
    }

    @Override
    public Person getItem(int position) {
        if(myList != null)
            return myList.get(position);
        return null;
    }

    @Override
    public long getItemId(int position) {
        if(myList != null)
            return myList.get(position).hashCode();
        return 0;

    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        Holder holder;

        //If the listview does not have an xml layout ready set the layout
        if (convertView == null){

            //we need a new holder to hold the structure of the cell
            holder = new Holder();

            //get the XML inflation service
            LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            //Inflate our xml cell to the convertView
            convertView = inflater.inflate(R.layout.person_cell, null);

            //Get xml components into our holder class
            holder.txtName = (TextView)convertView.findViewById(R.id.person_cell_txtName);
            holder.txtSurname = (TextView)convertView.findViewById(R.id.person_cell_txtSurname);
            holder.imageView = (ImageView)convertView.findViewById(R.id.person_cell_imageview);

            //Attach our holder class to this particular cell
            convertView.setTag(holder);

        }else{

            //The listview cell is not empty and contains already components loaded, get the tagged holder
            holder = (Holder)convertView.getTag();

        }

        //Fill our cell with data

        //get our person object from the list we passed to the adapter
        Person person = getItem(position);

        //Fill our view components with data
        holder.txtName.setText(person.getName());
        holder.txtSurname.setText(person.getSurname());

             Picasso.with(context).load(person.getImageUrl()).fit().into(holder.imageView);

        return convertView;
    }

    /**
     * This holder must replicate the components in the person_cell.xml 
     * We have a textview for the name and the surname and an imageview for the picture
     */
    private class Holder{

        TextView txtName;
        TextView txtSurname;
        ImageView imageView;

    }
}

然后在我们的活动,我们可以简单地填充我们的人对象的列表,并创建我们的适配器的一个实例,并将其设置为列表视图主适配器。

Then in our Activity we can simply populate our List of person objects and create an instance of our adapter and set it as the listview main adapter.

ListView myListView = new ListView(getApplicationContext());

List<Person> personList = new ArrayList<>();

Person person = new Person();

person.setName("John");
person.setSurname("Doe");
person.setImageUrl("https://lh3.googleusercontent.com/-Sa9kdnhuE5E/AAAAAAAAAAI/AAAAAAAAABs/ILmJ8_sk9aY/photo.jpg");

 MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.person_cell, personList);

myListView.setAdapter(adapter);

这基本上是一个自定义适配器背后的故事。

This is basically the story behind a custom adapter.

这篇关于Android的:如何设置ImageView的SRC在列表中动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆