在 Xml 解析如何将图像从可绘制对象加载到列表视图中

In Xml Parsing How to Load Image into a Listview from drawable

我正在尝试从服务器解析一个 xml,我成功地检索了一个数据并将其加载到列表视图中

但我想将单个图像从可绘制对象加载到列表视图

(ie) 在 drawable 中我有一个 orange.png 图像,我想将该图像加载到列表视图中,但我不知道该怎么做

这是我的代码

public class MainActivity extends AppCompatActivity {
    // All static variables
    static final String URL1 = "http://my_server_name.com/fruits";
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_TITLE = "title";
    static final String KEY_LINK = "link";

    URL url;
    URLConnection urlConnection;

    ListView listview;
    int images=R.drawable.radio;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 listview = (ListView) findViewById(R.id.list);

    new GetData().execute();
}

class GetData extends AsyncTask<String, String, String> {
    String xml = "error";

    @Override
    protected String doInBackground(String... params) {

        try {
            url = new URL(URL1);

            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = urlConnection.getInputStream();

            InputStreamReader isw = new InputStreamReader(in);

            BufferedReader br = new BufferedReader(isw);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();

            xml = sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return xml;
    }


    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is);


            NodeList nl = doc.getElementsByTagName(KEY_ITEM);
            for (int i = 0; i < nl.getLength(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);
                Log.e("TAg1", getValue(e, KEY_TITLE));
                //Log.e("TAg2", getValue(e, KEY_LINK));
                map.put(KEY_TITLE, getValue(e, KEY_TITLE));
                map.put(KEY_LINK, getValue(e, KEY_LINK));
                menuItems.add(map);
            }


        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());

        }

        ListAdapter adapter = new SimpleAdapter(getApplicationContext(), menuItems,
                R.layout.list_item,
                new String[]{KEY_TITLE, KEY_LINK}, new int[]{
                R.id.name});
        listview.setAdapter(adapter);


    }

    public final String getElementValue(Node elem) {
        Node child;
        if (elem != null) {
            if (elem.hasChildNodes()) {
                for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) {
                    if (child.getNodeType() == Node.TEXT_NODE) {
                        return child.getNodeValue();
                    }
                }
            }
        }
        return "";
    }

    public String getValue(Element item, String str) {
        NodeList n = item.getElementsByTagName(str);
        return this.getElementValue(n.item(0));
    }


}

layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"  >

    <ImageView
        android:paddingTop="20dp"
        android:layout_width="80dp"
        android:layout_height="70dp"
        android:id="@+id/imageView"
        android:src="@drawable/orange"
        android:paddingLeft="15dp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/name"
        android:layout_gravity="center_horizontal"
        android:textColor="#000000"
        android:paddingTop="15dp"

        android:layout_alignBottom="@+id/imageView"
        android:layout_toRightOf="@+id/imageView"
        android:layout_toEndOf="@+id/imageView" />

</RelativeLayout>

创建一个 class 自定义适配器

public class CustomAdapter extends BaseAdapter{   
    String [] result;
    Context context;
    private LayoutInflater inflater;

    public CustomAdapter(Context context, String[] text) {
        this.context = context;
        this.result = text;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return result.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public class Holder
    {
        TextView tv;
        ImageView img;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

         Holder holder;

        if (convertView == null) {
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.layout, null);
            holder = new Holder();
            holder.tv=(TextView) convertView.findViewById(R.id.name);
            holder.img=(ImageView) convertView.findViewById(R.id.imageView);  

            convertView.setTag(holder);
        } else {
            holder = (Holder) convertView.getTag();
        }

        holder.tv.setText(result[position]);
        holder.img.setImageResource(R.drawable.orange);         

        return convertView;
    }

}

对于数据数组

创建一个全局变量

ArrayList<String> title= new ArrayList<>();   

.

NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            Log.e("TAg1", getValue(e, KEY_TITLE));
            //Log.e("TAg2", getValue(e, KEY_LINK));
            map.put(KEY_TITLE, getValue(e, KEY_TITLE));
            map.put(KEY_LINK, getValue(e, KEY_LINK));
            menuItems.add(map);

            title.add(getValue(e, KEY_TITLE));
        }

并从您的 Activity class 调用此适配器

String[] dataArr = new String[title.size()];
dataArr = title.toArray(dataArr );
CustomAdapter adapter = new CustomAdapter(getApplicationContext(), dataArr );
listview.setAdapter(adapter);