如果我不理解你的答案,请和我一起露面,我还在学习Java和Android新手。
我有一个使用片段的标签布局的应用程序,在其中一个片段中我希望有一个双/多行列表视图,我一直在关注这个tutorial,它显示了{ {1}}。我已将代码复制到我的片段中,似乎无法使其工作。我所有用于片段布局的代码和两行与上面链接中的代码相同,但我想要显示列表的片段的Java类除外。
片段的代码如下:
ListActivity
给我错误的部分是
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
更改为ListFragment
时,错误不再存在
为什么它不起作用以及如何解决它?
答案 0 :(得分:1)
ListFragment不是Context的子类,而ListActivity是。您必须将某种类型的Context传递给此构造函数。例如,假设您的Activity(或FragmentActivity)类名为MainActivity
:
sa = new SimpleAdapter(MainActivity.this, list, ...
根据您创建此片段的时间可能不起作用,因此您可以将onCreate()
中的所有代码移至onActivityCreated()
方法并使用:
sa = new SimpleAdapter(getActivity(), list, ...