0

我有一个使用片段的选项卡布局的应用程序,在其中一个片段中我想要一个两行/多行列表视图,我一直在关注本教程,它显示了一个ListActivity. 我已将代码复制到我的片段中,但似乎无法让它工作。我用于片段布局的所有代码和两行代码与上面链接中的代码相同,但我想在其中显示列表的片段的 Java 类除外。

该片段的代码如下:

package com.example.shopsellswap;

import java.util.ArrayList;
import java.util.HashMap;
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.SimpleAdapter;

public class Fragment_My_Profile extends ListFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View myProfileView = inflater.inflate(R.layout.fragment_my_profile, container, false);


        return myProfileView;
    }

    //ArrayList holds the data (as HashMaps) to load into the ListView
        ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
        //SimpleAdapter does the work to load the data in to the ListView
        private SimpleAdapter sa;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            //HashMap links each line of data to the correct TextView
            HashMap<String,String> item;
            for(int i=0;i<StatesAndCapitals.length;i++){
              item = new HashMap<String,String>();
              item.put( "line1", StatesAndCapitals[i][0]);
              item.put( "line2", StatesAndCapitals[i][3]);
              list.add( item );
            }

            sa = new SimpleAdapter(Fragment_My_Profile.this, list,
                    R.layout.my_two_lines,
                    new String[] { "line1","line2" },
                    new int[] {R.id.line_a, R.id.line_b});

            setListAdapter(sa);
        }

        private String[][] StatesAndCapitals =
            {{"Alabama","Montgomery"},
            {"Alaska","Juneau"},
            {"Arizona","Phoenix"},
            {"Arkansas","Little Rock"},
            {"California","Sacramento"}};

给我错误的部分是

        sa = new SimpleAdapter(Fragment_My_Profile.this, list,
                R.layout.my_two_lines,
                new String[] { "line1","line2" },
                new int[] {R.id.line_a, R.id.line_b});

        setListAdapter(sa);

具体错误是:

The constructor SimpleAdapter(Fragment_My_Profile, ArrayList<HashMap<String,String>>, int, String[], int[]) is undefined

奇怪的是当我更改ListFragmentListActivity错误不再存在时

为什么它不起作用,我该如何解决?

4

1 回答 1

1

ListFragment 不是 Context 的子类,而 ListActivity 是。您必须将某种类型的 Context 传递给此构造函数。例如,假设您的 Activity(或 FragmentActivity)类名为MainActivity

sa = new SimpleAdapter(MainActivity.this, list, ...

根据您创建此片段的时间可能无法正常工作,因此您可以将所有代码移入onCreate()onActivityCreated()方法并使用:

sa = new SimpleAdapter(getActivity(), list, ...
于 2012-12-15T06:04:44.423 回答