【问题标题】:Individual background image for a listview generated using JSON on Android在 Android 上使用 JSON 生成的列表视图的单个背景图像
【发布时间】:2014-07-11 03:35:05
【问题描述】:

在进行了广泛的研究后,我仍然难以解决这个难题。 简而言之,我试图为从 JSON 数据生成的每个列表视图数组的项目创建一个背景图像。我已经在 J​​SON 中设置了背景图像的 url。 JSON 函数已经配置好了,因此我已经能够从在线源将数据填充到应用程序中。但是,它只是我无法提取的背景图像。我设法插入了一张图片,但不知道如何为每个列表视图部分设置不同的背景图片。

我也尝试过使用 XML 文件,但这并没有多大帮助。

下面是我的 MainActivity 的代码

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

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String LIST_ITEM_NAME = "list_item_name";
    static String COUNTRY = "country";
    static String LIST_ITEM_PRICE = "list_item_price";
    static String LIST_ITEM_BAC = "list_item_bac";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);
        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(MainActivity.this, "Loading.. Please Wait", 5000).show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunctions
                    .getJSONfromURL("http://dooba.ca/analytics/ed.php");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("list_item");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> retrieve = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    retrieve.put("list_item_bac", jsonobject.getString("list_item_bac"));
                    retrieve.put("list_item_name", jsonobject.getString("list_item_name"));
                    retrieve.put("country", jsonobject.getString("country"));
                    retrieve.put("list_item_price", jsonobject.getString("list_item_price"));

                    // Set the JSON Objects into the array
                    arraylist.add(retrieve);



                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(MainActivity.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);

        }
    }
}

MainActivity 还引用了我的 ListViewAdapter 类,因此,

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

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapter(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        imageLoader = new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView list_item_name;
        TextView country;
        TextView list_item_price;
        ImageView list_item_bac;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.listview_item, parent, false);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        list_item_name = (TextView) itemView.findViewById(R.id.list_item_name);
        country = (TextView) itemView.findViewById(R.id.country);
        list_item_price = (TextView) itemView.findViewById(R.id.list_item_price);

        // Locate the ImageView in listview_item.xml
        list_item_bac = (ImageView) itemView.findViewById(R.id.list_item_bac);

        // Capture position and set results to the TextViews
        list_item_name.setText(resultp.get(MainActivity.LIST_ITEM_NAME));
        country.setText(resultp.get(MainActivity.COUNTRY));
        list_item_price.setText(resultp.get(MainActivity.LIST_ITEM_PRICE));
        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class
        imageLoader.DisplayImage(resultp.get(MainActivity.LIST_ITEM_BAC), list_item_bac);
        // Capture ListView item click
        itemView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Get the position
                resultp = data.get(position);
                Intent intent = new Intent(context, SingleItemView.class);

                intent.putExtra("list_item_name", resultp.get(MainActivity.LIST_ITEM_NAME));

                intent.putExtra("country", resultp.get(MainActivity.COUNTRY));

                intent.putExtra("list_item_price",resultp.get(MainActivity.LIST_ITEM_PRICE));

                intent.putExtra("list_item_bac", resultp.get(MainActivity.LIST_ITEM_BAC));
                // Start SingleItemView Class
                context.startActivity(intent);

            }
        });
        return itemView;
    }
}

下面是 listview_item 和 listview_main 的 XML 文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:paddingTop="7dp"
    android:paddingBottom="7dp"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/ranklabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ranklabel" 
        android:textColor="#F0F0F0"/>

    <TextView
        android:id="@+id/list_item_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/ranklabel" 
        android:textColor="#F0F0F0"/>

    <TextView
        android:id="@+id/countrylabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ranklabel"
        android:text="@string/countrylabel" 
        android:textColor="#F0F0F0"/>

    <TextView
        android:id="@+id/country"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/list_item_name"
        android:layout_toRightOf="@+id/countrylabel" 
        android:textColor="#F0F0F0"/>

    <TextView
        android:id="@+id/populationlabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/countrylabel"
        android:text="@string/populationlabel" 
        android:textColor="#F0F0F0"/>

    <TextView
        android:id="@+id/list_item_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/country"
        android:layout_toRightOf="@+id/populationlabel" 
        android:shadowColor="#000000"
        android:shadowDx="-2"
        android:shadowDy="2"
        android:shadowRadius="0.01"
        android:textColor="#f2f2f2"/>

    <ImageView
        android:id="@+id/list_item_bac"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="0dp"
        android:background="#000000"
        android:alpha="0.8" />

</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:background="@drawable/graybac">

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:divider="@drawable/divider"
        android:dividerPadding="12dip"
        android:showDividers="middle"
        />

</RelativeLayout>

任何帮助或指导将不胜感激。

如果您需要澄清,请告诉我。 提前致谢

更新。下面是我的 JSON 文件

$arr[list_item] = array(
    array(
        "list_item_bac" => "http://dooba.ca/analytics/boathouse.png",
        "list_item_name" => "The Boat house",
         "country" => "Thursday, July 14",
        "list_item_price" => "5$"
    ),
     array(
        "list_item_bac" => "http://cdn1.sciencefiction.com/wp-content/uploads/2014/05/X-Men1.jpg",
        "list_item_name" => "Movie at ScotiaBank",
        "country" => "bobby",
        "list_item_price" => "10$"
    ),
    array(
        "list_item_bac" => "http://assets.vancitybuzz.com/wp-content/uploads/2014/04/Screen-Shot-2014-04-07-at-7.08.13-PM-880x600.png?a9d4bc",
        "list_item_name" => "Bastille liveshow",
        "country" => "bobby",
         "list_item_price" => "10$"
    ),

     array(
        "list_item_bac" => "http://vancouverfoodster.com/wp-content/uploads/2010/03/Fish-House-afternoon-tea-015.jpg",
        "list_item_name" => "The Fish House In Stanley Park",
        "country" => "bobby",
        "list_item_price" => "10$"
    ),

     array(
        "list_item_bac" => "http://vancouverfoodster.com/wp-content/uploads/2010/03/Fish-House-afternoon-tea-015.jpg",
        "list_item_name" => "test list_item_name",
        "country" => "bobby",
        "list_item_price" => "10$"
    ),

     array(
        "list_item_bac" => "http://vancouverfoodster.com/wp-content/uploads/2010/03/Fish-House-afternoon-tea-015.jpg",
        "list_item_name" => "test list_item_name",
        "country" => "bobby",
        "list_item_price" => "10$"
    ),

     array(
        "list_item_bac" => "http://www.dinemagazine.ca/wp-content/uploads/2012/09/labitoir3.jpg",
        "list_item_name" => "l'abbatoir",
        "country" => "bobby",
        "list_item_price" => "10$"
    ),

     array(
        "list_item_bac" => "http://www.dinemagazine.ca/wp-content/uploads/2012/09/labitoir3.jpg",
        "list_item_name" => "test list_item_name",
        "country" => "bobby",
        "list_item_price" => "10$"
    ),

     array(
        "list_item_bac" => "http://www.dinemagazine.ca/wp-content/uploads/2012/09/labitoir3.jpg",
        "list_item_name" => "test list_item_name",
        "country" => "bobby",
        "list_item_price" => "10$"
    ),

     array(
        "list_item_bac" => "http://www.dinemagazine.ca/wp-content/uploads/2012/09/labitoir3.jpg",
        "list_item_name" => "test list_item_name",
        "country" => "bobby",
        "list_item_price" => "10$"
    )
);

echo json_encode($arr);

以及JSON函数类

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

更新 2:

我试图创建一个线程来下载图像以供以后使用它有背景

public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView list_item_name;
        TextView country;
        TextView list_item_price;
        ImageView list_item_bac;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.listview_item, parent, false);
        RelativeLayout rootRelativeLayout=itemView.findViewById(R.id.rootRelativeLayout);

            new AsyncTask<Void, Void, Void>() {

                            @Override
                            protected Void doInBackground(Void... params) {
                                        Bitmap img = imageLoader.loadImageSync(list_item_bac);

                                return null;
                            }

                            protected void onPostExecute(Void result) {

        rootRelativeLayout.setBackgroundDrawable();
 }

非常感谢。

更新 3

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

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables

    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapter(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        imageLoader = new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView list_item_name;
        TextView country;
        TextView list_item_price;
        ImageView list_item_bac;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.listview_item, parent, false);
        RelativeLayout rootRelativeLayout=itemView.findViewById(R.id.rootRelativeLayout);

            new AsyncTask<rootRelativeLayout>() {

                            @Override
                            protected Void doInBackground(Void... params) {
                                        Bitmap img = imageLoader.loadImageSync(list_item_bac);

                                return null;
                            }

                            protected void onPostExecute(Void result) {
                                Drawable d = new BitmapDrawable(Resources, Bitmap);
                            }
            };

        rootRelativeLayout.setBackground(null);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        list_item_name = (TextView) itemView.findViewById(R.id.list_item_name);
        country = (TextView) itemView.findViewById(R.id.country);
        list_item_price = (TextView) itemView.findViewById(R.id.list_item_price);

        // Locate the ImageView in listview_item.xml
        list_item_bac = (ImageView) itemView.findViewById(R.id.list_item_bac);

        // Capture position and set results to the TextViews
        list_item_name.setText(resultp.get(MainActivity.LIST_ITEM_NAME));
        country.setText(resultp.get(MainActivity.COUNTRY));
        list_item_price.setText(resultp.get(MainActivity.LIST_ITEM_PRICE));
        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class
        imageLoader.DisplayImage(resultp.get(MainActivity.LIST_ITEM_BAC), list_item_bac);
        // Capture ListView item click
        itemView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Get the position
                resultp = data.get(position);
                Intent intent = new Intent(context, SingleItemView.class);

                intent.putExtra("list_item_name", resultp.get(MainActivity.LIST_ITEM_NAME));

                intent.putExtra("country", resultp.get(MainActivity.COUNTRY));

                intent.putExtra("list_item_price",resultp.get(MainActivity.LIST_ITEM_PRICE));

                intent.putExtra("list_item_bac", resultp.get(MainActivity.LIST_ITEM_BAC));
                // Start SingleItemView Class
                context.startActivity(intent);

            }
        });
        return itemView;
    }
}

更新 4

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

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables

    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapter(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        imageLoader = new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView list_item_name;
        TextView country;
        TextView list_item_price;
        ImageView list_item_bac;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.listview_item, parent, false);
        RelativeLayout rootRelativeLayout=(RelativeLayout) itemView.findViewById(R.id.rootRelativeLayout);

        new ImageDownloadTask(rootRelativeLayout,"http://dooba.ca/analytics/ed.php").execute();
        //rootRelativeLayout.setBackground(null);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        list_item_name = (TextView) itemView.findViewById(R.id.list_item_name);
        country = (TextView) itemView.findViewById(R.id.country);
        list_item_price = (TextView) itemView.findViewById(R.id.list_item_price);

        // Locate the ImageView in listview_item.xml
        list_item_bac = (ImageView) itemView.findViewById(R.id.list_item_bac);

        // Capture position and set results to the TextViews
        list_item_name.setText(resultp.get(MainActivity.LIST_ITEM_NAME));
        country.setText(resultp.get(MainActivity.COUNTRY));
        list_item_price.setText(resultp.get(MainActivity.LIST_ITEM_PRICE));
        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class
        imageLoader.DisplayImage(resultp.get(MainActivity.LIST_ITEM_BAC), list_item_bac);
        // Capture ListView item click
        itemView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Get the position
                resultp = data.get(position);
                Intent intent = new Intent(context, SingleItemView.class);

                intent.putExtra("list_item_name", resultp.get(MainActivity.LIST_ITEM_NAME));

                intent.putExtra("country", resultp.get(MainActivity.COUNTRY));

                intent.putExtra("list_item_price",resultp.get(MainActivity.LIST_ITEM_PRICE));

                intent.putExtra("list_item_bac", resultp.get(MainActivity.LIST_ITEM_BAC));
                // Start SingleItemView Class
                context.startActivity(intent);

            }
        });
        return itemView;
    }
    AsyncTask<View,View,View> mytask= new AsyncTask<View,View,View>() {

        @Override
        protected View doInBackground(View... params) {
                    Bitmap img = imageLoader.loadImageSync(list_item_bac);

            return null;
        }
    };

    class ImageDownloadTask extends AsyncTask<View, View, View>
    {
        RelativeLayout mrelativelayout;
        String downloadUrl;
         Bitmap img;
        public ImageDownloadTask(RelativeLayout layout,String url)
        {

            mrelativelayout=layout;
            downloadUrl=url;
        }
        @Override
        protected View doInBackground(View... params) {
            // TODO Auto-generated method stub
            img = imageLoader.loadImageSync(downloadUrl);
            return null;
        }
          protected void onPostExecute(Void result) {
                Drawable d = new BitmapDrawable(context.getResources(), img);
                mrelativelayout.setBackground(d);
            }
    }
    }

【问题讨论】:

  • 背景图片的url存储在哪里??你在哪里存储了背景图片??
  • 您好,感谢您的回复。背景图像 url 存储在 JSON 文件的数组中。我已经用该文件的副本以及 android JSON 函数类更新了我的初始帖子。

标签: android arrays json listview android-listview


【解决方案1】:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" 
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="7dp"
android:id="@+id/rootRelativeLayout"
android:paddingBottom="7dp"
android:orientation="vertical" >
<TextView
    android:id="@+id/ranklabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/ranklabel" 
    android:textColor="#F0F0F0"/>

<TextView
    android:id="@+id/list_item_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/ranklabel" 
    android:textColor="#F0F0F0"/>

<TextView
    android:id="@+id/countrylabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/ranklabel"
    android:text="@string/countrylabel" 
    android:textColor="#F0F0F0"/>

<TextView
    android:id="@+id/country"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/list_item_name"
    android:layout_toRightOf="@+id/countrylabel" 
    android:textColor="#F0F0F0"/>

<TextView
    android:id="@+id/populationlabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/countrylabel"
    android:text="@string/populationlabel" 
    android:textColor="#F0F0F0"/>

<TextView
    android:id="@+id/list_item_price"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/country"
    android:layout_toRightOf="@+id/populationlabel" 
    android:shadowColor="#000000"
    android:shadowDx="-2"
    android:shadowDy="2"
    android:shadowRadius="0.01"
    android:textColor="#f2f2f2"/>

<ImageView
    android:id="@+id/list_item_bac"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="0dp"
    android:background="#000000"
    android:alpha="0.8" />

在 Java 代码中

 public View getView(final int position, View convertView, ViewGroup parent) {
    // Declare Variables
    TextView list_item_name;
    TextView country;
    TextView list_item_price;
    ImageView list_item_bac;

    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View itemView = inflater.inflate(R.layout.listview_item, parent, false);
    RelativeLayout rootRelativeLayout=itemView.findViewById(R.id.rootRelativeLayout);
    rootRelativeLayout.setBackgroundDrawable();
    }

试试这个

公共类 ListViewAdapter 扩展 BaseAdapter {

// Declare Variables

Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();

public ListViewAdapter(Context context,
        ArrayList<HashMap<String, String>> arraylist) {
    this.context = context;
    data = arraylist;
    imageLoader = new ImageLoader(context);
}

@Override
public int getCount() {
    return data.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

public View getView(final int position, View convertView, ViewGroup parent) {
    // Declare Variables
    TextView list_item_name;
    TextView country;
    TextView list_item_price;
    ImageView list_item_bac;

    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View itemView = inflater.inflate(R.layout.listview_item, parent, false);
    RelativeLayout rootRelativeLayout=itemView.findViewById(R.id.rootRelativeLayout);

    new ImageDownloadTask(rootRelativeLayout,/*Image Download URl here*/).execute();
    //rootRelativeLayout.setBackground(null);
    // Get the position
    resultp = data.get(position);

    // Locate the TextViews in listview_item.xml
    list_item_name = (TextView) itemView.findViewById(R.id.list_item_name);
    country = (TextView) itemView.findViewById(R.id.country);
    list_item_price = (TextView) itemView.findViewById(R.id.list_item_price);

    // Locate the ImageView in listview_item.xml
    list_item_bac = (ImageView) itemView.findViewById(R.id.list_item_bac);

    // Capture position and set results to the TextViews
    list_item_name.setText(resultp.get(MainActivity.LIST_ITEM_NAME));
    country.setText(resultp.get(MainActivity.COUNTRY));
    list_item_price.setText(resultp.get(MainActivity.LIST_ITEM_PRICE));
    // Capture position and set results to the ImageView
    // Passes flag images URL into ImageLoader.class
    imageLoader.DisplayImage(resultp.get(MainActivity.LIST_ITEM_BAC), list_item_bac);
    // Capture ListView item click
    itemView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Get the position
            resultp = data.get(position);
            Intent intent = new Intent(context, SingleItemView.class);

            intent.putExtra("list_item_name", resultp.get(MainActivity.LIST_ITEM_NAME));

            intent.putExtra("country", resultp.get(MainActivity.COUNTRY));

            intent.putExtra("list_item_price",resultp.get(MainActivity.LIST_ITEM_PRICE));

            intent.putExtra("list_item_bac", resultp.get(MainActivity.LIST_ITEM_BAC));
            // Start SingleItemView Class
            context.startActivity(intent);

        }
    });
    return itemView;
}
AsyncTask<View,View,View> mytask= new AsyncTask<View,View,View>() {

    @Override
    protected View doInBackground(View... params) {
                Bitmap img = imageLoader.loadImageSync(list_item_bac);

        return null;
    }

};

class ImageDownloadTask extends AsyncTask<View, View, View>
{
    RelativeLayout mrelativelayout;
    String downloadUrl;
     Bitmap img;
    public ImageDownloadTask(RelativeLayout layout,String url)
    {

        mrelativelayout=layout;
        downloadUrl=url;
    }
    @Override
    protected View doInBackground(View... params) {
        // TODO Auto-generated method stub
        img = imageLoader.loadImageSync(downloadUrl);
        return null;
    }
      protected void onPostExecute(Void result) {
            Drawable d = new BitmapDrawable(context.getResources(), img);
            mrelativelayout.setBackground(d);
        }
}

}

【讨论】:

  • 在此之前,您需要从 url 下载图像并将其保存到应用程序目录中
  • 您好软件,非常感谢您的帮助。问题是我希望每个数组的背景图像根据 JSON 文件中给出的带有字符串“list_item_bac”的 url 图像链接自动更新,而不是将图像下载到我的本地应用程序目录中。
  • 是啊,在 rootRelativeLayout.setBackgroundDrawable(); 之前语句启动一个线程来下载图像,然后将该图像设置为 relativelayoutbackground
  • 我承认我不是这方面的专家,感谢您有争议的帮助。我尝试应用您的上述建议,我尝试生成的代码可以在我最初帖子的更新部分中找到(太长,无法在评论中发布)。此外,setBackgroundDrawable() 方法似乎已被弃用并替换为 setBackground(background 或 null)。如果你能在这件事上进一步帮助我,我会很高兴的。
  • stackoverflow.com/a/4560707/1696704 点击此链接并从位图创建可绘制对象并将其设置为 rootRelativelayout 背景
猜你喜欢
  • 2015-06-10
  • 2015-07-04
  • 1970-01-01
  • 2014-02-25
  • 1970-01-01
  • 1970-01-01
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多