如何将ListView放入片段中

时间:2014-03-13 10:32:12

标签: java android listview android-fragments android-listview

我试图将ListView放入片段中,但我的应用崩溃了。 我跟着this guide学习了如何在活动中放置ListView,但是我想把它放在一个片段中,所以我稍微改了一下代码。 这是我的片段:

公共类FaqFragment扩展了Fragment {

public static Fragment newInstance() {
    FaqFragment fragment = new FaqFragment();
    Bundle args = new Bundle();
    fragment.setArguments(args);
    return fragment;
}

private ListView listView1;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_faq, container, false);

    Element element_data[] = new Element[]
    {
        new Element(R.drawable.goccia, "Goccia1"),
        new Element(R.drawable.goccia, "Goccia2"),
        new Element(R.drawable.goccia, "Goccia3"),
        new Element(R.drawable.goccia, "Goccia4"),
        new Element(R.drawable.goccia, "Goccia5")
    };

    ElementAdapter adapter = new ElementAdapter(getActivity(), android.R.layout.simple_list_item_1, element_data);


    listView1 = (ListView)v.findViewById(R.id.listView1);

    View header = (View)getLayoutInflater(savedInstanceState).inflate(R.layout.element, null);
    listView1.addHeaderView(header);

    listView1.setAdapter(adapter);

    return v;
}

这是我的ArrayAdapter

public class ElementAdapter extends ArrayAdapter<Element>{

FragmentActivity context; 
int layoutResourceId;    
Element data[] = null;

public ElementAdapter(FragmentActivity fragmentActivity, int layoutResourceId, Element[] data) {
    super(fragmentActivity, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = fragmentActivity;
    this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    WeatherHolder holder = null;

    if(row == null)
    {
        LayoutInflater inflater = ((FragmentActivity)context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);

        holder = new WeatherHolder();
        holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
        holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);

        row.setTag(holder);
    }
    else
    {
        holder = (WeatherHolder)row.getTag();
    }

    Element element = data[position];
    holder.txtTitle.setText(element.title);
    holder.imgIcon.setImageResource(element.icon);

    return row;
}

static class WeatherHolder
{
    ImageView imgIcon;
    TextView txtTitle;
}

}

这是我的Element

public class Element {
public int icon;
public String title;
public Element(){
    super();
}

public Element(int icon, String title) {
    super();
    this.icon = icon;
    this.title = title;
}

}

该应用有3个标签,当我滑动到标签时,应用程序崩溃,我已经写过的代码(片段)。

在logcat中存在以下错误:

  

03-13 11:25:39.455:E / AndroidRuntime(2840):at   com.example.bluhackathon.ElementAdapter.getView(ElementAdapter.java:47)

我尝试删除ArrayAdapter的第47,48和49行,但应用没有崩溃(当然有一个包含空元素的列表。

第47,48,49行:

Element element = data[position];
    holder.txtTitle.setText(element.title);
    holder.imgIcon.setImageResource(element.icon);

2 个答案:

答案 0 :(得分:1)

你可以使用ListFragment来实现它,下面是我实现“将listview放入Fragment,并从MySQL获取数据”的答案,我昨天写了它并希望它可以帮助你解决问题。

    package com.ecnu.vendingmachine;

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

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.ecnu.vendingmachine.widgets.JSONParser;

public class VendingFragment extends ListFragment {

    private String Tag = "VendingFragment";
    private static final String TAG_SUCCESS = "success";

    private ListView listView;

    // Progress Dialog
    private ProgressDialog pDialog;
    // Creating JSON Parser object
    JSONParser jsonParser = new JSONParser();
    JSONArray vendingmachine = null;

    ArrayList<HashMap<String, String>> vendinglist;

    // url to get all products list
    MainActivity main = new MainActivity();
    private String url_all_vendingmachine = main.getIP()
            + "vendingmachine/get_all_vendingmachine.php";

    // products JSONArray

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        return inflater.inflate(R.layout.vending_main, container, false);
    }

     @Override 
     public void onViewCreated (View view, Bundle savedInstanceState) {

        vendinglist = new ArrayList<HashMap<String, String>>();
        //listView = (ListView) view.findViewById(R.id.list);

        listView = getListView();
        new get_all_vendingmachine().execute();
    }   

    class get_all_vendingmachine extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            Log.i(Tag, "pDialog");
        }

        protected String doInBackground(String... args) {

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            Log.i(Tag, url_all_vendingmachine);
            // getting JSON Object
            // Note that create product url accepts POST method

            JSONObject json = jsonParser.makeHttpRequest(
                    url_all_vendingmachine, "GET", params);

            // check log cat for response
            Log.i(Tag, json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // Ada record Data (SUCCESS = 1)
                    // Getting Array of vendingmachine
                    vendingmachine = json.getJSONArray("vendings");

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

                        // Storing each json item in variable
                        String id = c.getString("VMid");
                        String name = c.getString("Name");
                        String address = c.getString("Address");
                        Log.i(Tag, id);
                        Log.i(Tag, name);
                        Log.i(Tag, address);
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        // adding each child node to HashMap key => value
                        map.put("VMid", id);
                        map.put("Name", name);
                        map.put("Address", address);

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

                } else {
                    // failed to create product
                    getActivity().finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // updating listview
                    // HashMap<String, String>中的key
                    String[] from = { "Name", "Address", "VMid" };
                    // list_item.xml中对应的控件ID
                    int[] to = { R.id.vending_name, R.id.vending_address,
                            R.id.vending_id };
                    Log.i(Tag, from[0]);
                    SimpleAdapter adapter = new SimpleAdapter(getActivity(),
                            vendinglist, R.layout.vending_list, from, to);
                    listView.setAdapter(adapter);
                }
            });
        }

    }

}

vending_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:background="@color/whiteColor" >

    <include
        android:id="@+id/layout_buy_title_actionbar"
        layout="@layout/headbar_title" />

    <ListView
        android:id="@id/android:list"
        android:layout_below="@id/layout_buy_title_actionbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:cacheColorHint="@android:color/transparent"
        android:divider="@drawable/reader_item_divider"
        android:listSelector="@android:color/transparent" >
    </ListView>

</RelativeLayout>

vending_list.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="@dimen/selectVmListCell_Height"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="@dimen/selectVmListCell_Height"
        android:layout_gravity="center_vertical"
        android:background="@drawable/bg_listview"
        android:gravity="center_vertical"
        android:paddingLeft="@dimen/layout_Margin_10" >

        <LinearLayout
            android:id="@+id/imageTypeLayout"
            android:layout_width="@dimen/smallImage_HW_45"
            android:layout_height="fill_parent"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:gravity="center_vertical"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/vendingImage"
                style="@style/smallImageStyle"
                android:src="@drawable/buy_main_not_shop" />

            <TextView
                android:id="@+id/distanceText"
                style="@style/smallTxtStyle"
                android:layout_gravity="center_horizontal"
                android:gravity="center"
                android:singleLine="true"
                android:textColor="@color/lightOrangeColor" />
        </LinearLayout>

        <RelativeLayout
            android:id="@+id/vendingSave"
            android:layout_width="47.0dip"
            android:layout_height="fill_parent"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true" >

            <ImageView
                android:id="@+id/vendingSaveImage"
                android:layout_width="27.0dip"
                android:layout_height="27.0dip"
                android:layout_centerInParent="true"
                android:layout_centerVertical="true"
                android:background="@drawable/bg_favor_btn" />
        </RelativeLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_centerVertical="true"
            android:layout_marginLeft="@dimen/layout_Margin_10"
            android:layout_toLeftOf="@id/vendingSave"
            android:layout_toRightOf="@id/imageTypeLayout"
            android:gravity="center_vertical"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/vending_name"
                style="@style/midDarkGrayTxtStyle"
                android:layout_width="fill_parent" />

            <TextView
                android:id="@+id/vending_address"
                style="@style/smallLightGrayTxtStyle"
                android:layout_width="fill_parent"
                android:maxLines="2" />

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >

                <TextView
                    style="@style/smallLightGrayTxtStyle"
                    android:text="Number:" />

                <TextView
                    android:id="@+id/vending_id"
                    style="@style/smallLightGrayTxtStyle" />
            </LinearLayout>
        </LinearLayout>
    </RelativeLayout>

</LinearLayout>

希望它可以帮助您找到如何将listview放入片段中。 我的listview中的元素很复杂,如果你只想要一行,它比我编码的更简单。

答案 1 :(得分:0)

尝试使用ListFragment,或者您可以关注vogella的this指南