类扩展片段和列表视图

时间:2013-01-08 11:35:06

标签: android android-fragments listactivity android-listfragment

我正在尝试使用片段创建一个选项卡,这些片段将在解析xml页面后显示一个条目列表。但是我无法在tab类中扩展listactivity,因为它已经扩展了fragment.I已经尝试实现了listfragments,但它给了我一个关于ListAdapter的错误:新的SimpleAdapter说“构造函数SimpleAdapter(Protab1,ArrayList>,int ,String [],int [])未定义“。请你帮帮我。

package com.example.pro1;
import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class Protab1 extends ListFragment {
    // All static variables
        static final String URL = "http://api.androidhive.info/pizza/?format=xml";
        // XML node keys
        static final String KEY_ITEM = "item"; // parent node
        static final String KEY_ID = "id";
        static final String KEY_NAME = "name";
        static final String KEY_COST = "cost";
        static final String KEY_DESC = "description";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.protab1, container, false);
        ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_ITEM);
        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
            map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
            map.put(KEY_DESC, parser.getValue(e, KEY_DESC));

            // adding HashList to ArrayList
            menuItems.add(map);
        }

        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, menuItems,
                R.layout.list_item,
                new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
                        R.id.name, R.id.desciption, R.id.cost });

        setListAdapter(adapter);

        }

}

1 个答案:

答案 0 :(得分:1)

尝试使用this.getActivity()代替this作为SimpleAdapter的第一个参数。第一个参数采用Context对象,但由于ListFragment(或任何Fragment)不扩展Context,因此它不起作用。