使用自定义数组适配器
Using custom array adapter
我正在学习使用自定义适配器,我认为我正朝着正确的方向前进,直到我对 class 自定义适配器的构造函数的超级方法有疑问。你能找出背后的问题吗?
在此之前,我使用了 Simple Adapter,但我希望更灵活地控制布局。
这是我的 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="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<!-- Name Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello This is testing"
android:id="@+id/guid"
android:visibility="gone"/>
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:text="name:"
android:textStyle="bold"
android:visibility="gone"/>
<!-- Email label -->
<TextView
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:text="email"
android:textStyle="bold"
/>
<!-- Mobile number label -->
<TextView
android:id="@+id/mobile"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:text="Mobile: "
android:textColor="#5d5d5d"
android:maxLines="1"/>
</LinearLayout>
这是我的片段class
public class NewsFragment extends Fragment{
private ProgressDialog pDialog;// Progress Dialog
ListView newsList;
ArrayList<HashMap<String, String>> postList; //Declare Array
private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/get_news.php";
GetNews.CustomAdapter CA;
// JSON Node names
private static final String TAG_ID = "id";
private static final String POST_ALLPOSTS = "posts";
private static final String POST_ID = "ID";
private static final String POST_TITLE = "post_title";
private static final String POST_CONTENT = "post_content";
private static final String GUID = "guid";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.news, container, false);
newsList = (ListView) view.findViewById(R.id.newsListView);
TextView topic = (TextView) view.findViewById(R.id.topic);
postList = new ArrayList<HashMap<String, String>>();
//Get arguments
Bundle args = getArguments();
String mytopic = args.getString("Topic");
//Set topic
topic.setText(mytopic.toUpperCase());
//Execute getContacts
new GetNews().execute();
newsList.setOnItemClickListener(new newsListClick());
return view;
}
public class newsListClick implements ListView.OnItemClickListener{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("News List","Clicked " + id);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SinglePost singleFrag = new SinglePost();
fragmentTransaction.replace(R.id.content_frame, singleFrag);
fragmentTransaction.commit();
}
}
//Async Task
private class GetNews extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Strings","Checking Json");
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// contacts JSONArray
JSONArray posts = null;
// Getting JSON Array node
posts = jsonObj.getJSONArray(POST_ALLPOSTS);
// looping through All Contacts
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
Log.d("Post->",posts.getJSONObject(i).toString());
String id = c.getString(POST_ID);
Log.d("Post->ID",id);
String post_title = c.getString(POST_TITLE);
String post_content = c.getString(POST_CONTENT);
String guid = c.getString(GUID);
Log.d("GUID->",guid);
//String gender = c.getString(TAG_GENDER);
// tmp hashmap for single post
HashMap<String, String> post = new HashMap<String, String>();
// adding each child node to HashMap key => value
post.put(POST_ID, id);
post.put(POST_TITLE, post_title);
post.put(POST_CONTENT, post_content);
post.put(GUID, guid);
// adding contact to contact list
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Updating parsed JSON data into ListView
/*
ListAdapter adapter = new SimpleAdapter(getActivity(), postList, R.layout.list_item,
new String[] { POST_TITLE,POST_CONTENT, GUID },
new int[] {R.id.email, R.id.mobile, R.id.guid });
*/
CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
newsList.setAdapter(CA);
}
public class CustomAdapter extends ArrayAdapter<HashMap<String, String>>{
public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
//something is wrong with super
super(context, resource, objects);
}
public View getView(int position, View convertView, ViewGroup Parent){
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
}
HashMap<String, String> objects = new HashMap<String, String>();
TextView thisview = (TextView) convertView.findViewById(R.id.email);
thisview.setText(objects.get(position).get(POST_TITLE));
return convertView;
}
}//
}
}
更改此行
CA = new CustomAdapter(this, R.layout.list_item, postList);
到
CA = new CustomAdapter(getActivity(), R.layout.list_item, postList);
注意: 当您使用 Fragment
时,您应该使用 getActivity()
作为 Context
。
另外请记住,您使用的是 HashMap<String,String>
,因此您的 ArrayAdapter
将是 ArrayAdapter<HashMap<String, String>>
而不是 ArrayAdapter<String>
。
您正在扩展 ArrayAdapter<String>
并将 ArrayList 作为构造函数参数传递。它们必须是同一类型。
此外,您需要传递 Context
而不是您的异步任务 GetNews
。
您还可以查看 BaseAdapter,其中不需要将任何数组作为构造函数参数传递。
要扩展 Piyush 的答案,您还需要修改 CustomAdapter
构造函数
来自这里:
public CustomAdapter(GetNews context, ... ) { }
至此
public CustomAdapter(Context context, ... ) { }
这是因为 getActivity()
将 return 一个 Activity
,它是 Context
class 的实例 - 不是 [=16 的实例=]
private ArrayList<HashMap<String, String>> mList;
public void setmList(ArrayList<HashMap<String, String>> mList) {
this.mList = mList;
}
public CustomAdapter(Context context, int resource) {
//something is wrong with super
super(context, resource);
}
并用设置列表初始化它
CA = new CustomAdapter(getActivity, R.layout.list_item);
CA.setmList(yourlist);
不知道为什么带有三个参数的 super 在这种情况下不起作用,但它肯定会解决您的问题
我正在学习使用自定义适配器,我认为我正朝着正确的方向前进,直到我对 class 自定义适配器的构造函数的超级方法有疑问。你能找出背后的问题吗? 在此之前,我使用了 Simple Adapter,但我希望更灵活地控制布局。 这是我的 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="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<!-- Name Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello This is testing"
android:id="@+id/guid"
android:visibility="gone"/>
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:text="name:"
android:textStyle="bold"
android:visibility="gone"/>
<!-- Email label -->
<TextView
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:text="email"
android:textStyle="bold"
/>
<!-- Mobile number label -->
<TextView
android:id="@+id/mobile"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:text="Mobile: "
android:textColor="#5d5d5d"
android:maxLines="1"/>
</LinearLayout>
这是我的片段class
public class NewsFragment extends Fragment{
private ProgressDialog pDialog;// Progress Dialog
ListView newsList;
ArrayList<HashMap<String, String>> postList; //Declare Array
private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/get_news.php";
GetNews.CustomAdapter CA;
// JSON Node names
private static final String TAG_ID = "id";
private static final String POST_ALLPOSTS = "posts";
private static final String POST_ID = "ID";
private static final String POST_TITLE = "post_title";
private static final String POST_CONTENT = "post_content";
private static final String GUID = "guid";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.news, container, false);
newsList = (ListView) view.findViewById(R.id.newsListView);
TextView topic = (TextView) view.findViewById(R.id.topic);
postList = new ArrayList<HashMap<String, String>>();
//Get arguments
Bundle args = getArguments();
String mytopic = args.getString("Topic");
//Set topic
topic.setText(mytopic.toUpperCase());
//Execute getContacts
new GetNews().execute();
newsList.setOnItemClickListener(new newsListClick());
return view;
}
public class newsListClick implements ListView.OnItemClickListener{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("News List","Clicked " + id);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SinglePost singleFrag = new SinglePost();
fragmentTransaction.replace(R.id.content_frame, singleFrag);
fragmentTransaction.commit();
}
}
//Async Task
private class GetNews extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Strings","Checking Json");
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// contacts JSONArray
JSONArray posts = null;
// Getting JSON Array node
posts = jsonObj.getJSONArray(POST_ALLPOSTS);
// looping through All Contacts
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
Log.d("Post->",posts.getJSONObject(i).toString());
String id = c.getString(POST_ID);
Log.d("Post->ID",id);
String post_title = c.getString(POST_TITLE);
String post_content = c.getString(POST_CONTENT);
String guid = c.getString(GUID);
Log.d("GUID->",guid);
//String gender = c.getString(TAG_GENDER);
// tmp hashmap for single post
HashMap<String, String> post = new HashMap<String, String>();
// adding each child node to HashMap key => value
post.put(POST_ID, id);
post.put(POST_TITLE, post_title);
post.put(POST_CONTENT, post_content);
post.put(GUID, guid);
// adding contact to contact list
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Updating parsed JSON data into ListView
/*
ListAdapter adapter = new SimpleAdapter(getActivity(), postList, R.layout.list_item,
new String[] { POST_TITLE,POST_CONTENT, GUID },
new int[] {R.id.email, R.id.mobile, R.id.guid });
*/
CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
newsList.setAdapter(CA);
}
public class CustomAdapter extends ArrayAdapter<HashMap<String, String>>{
public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
//something is wrong with super
super(context, resource, objects);
}
public View getView(int position, View convertView, ViewGroup Parent){
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
}
HashMap<String, String> objects = new HashMap<String, String>();
TextView thisview = (TextView) convertView.findViewById(R.id.email);
thisview.setText(objects.get(position).get(POST_TITLE));
return convertView;
}
}//
}
}
更改此行
CA = new CustomAdapter(this, R.layout.list_item, postList);
到
CA = new CustomAdapter(getActivity(), R.layout.list_item, postList);
注意: 当您使用 Fragment
时,您应该使用 getActivity()
作为 Context
。
另外请记住,您使用的是 HashMap<String,String>
,因此您的 ArrayAdapter
将是 ArrayAdapter<HashMap<String, String>>
而不是 ArrayAdapter<String>
。
您正在扩展 ArrayAdapter<String>
并将 ArrayList 作为构造函数参数传递。它们必须是同一类型。
此外,您需要传递 Context
而不是您的异步任务 GetNews
。
您还可以查看 BaseAdapter,其中不需要将任何数组作为构造函数参数传递。
要扩展 Piyush 的答案,您还需要修改 CustomAdapter
构造函数
来自这里:
public CustomAdapter(GetNews context, ... ) { }
至此
public CustomAdapter(Context context, ... ) { }
这是因为 getActivity()
将 return 一个 Activity
,它是 Context
class 的实例 - 不是 [=16 的实例=]
private ArrayList<HashMap<String, String>> mList;
public void setmList(ArrayList<HashMap<String, String>> mList) {
this.mList = mList;
}
public CustomAdapter(Context context, int resource) {
//something is wrong with super
super(context, resource);
}
并用设置列表初始化它
CA = new CustomAdapter(getActivity, R.layout.list_item);
CA.setmList(yourlist);
不知道为什么带有三个参数的 super 在这种情况下不起作用,但它肯定会解决您的问题