我有一个MainActivity
,它有一个导航抽屉,可以调用片段来加载ListView
。 ListView
将xml称为listitem的布局。我从Web服务获取数据,并希望在每个列表项上显示4个数据。我在一些教程中提到了CustomAdapter
以显示数据。我的问题是我将数据存储到String
数组,并且不知道如何将其放入我创建的对象中,然后传递给Adapter
然后显示
主要活动
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Recycle the typed array
navMenuIcons.recycle();
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new SearchFragment();
break;
case 2:
fragment = new SignInFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}
使用listview调用xml的HOME FRAGMENT
public class HomeFragment extends Fragment {
/*Layout Variables*/
protected ProgressBar mProgressBar;
protected JSONArray blogPostData;
protected TextView mTextView;
/*Variables to be displayed*/
protected String[] blogPostTitle;
protected String[] blogPostDate;
protected String[] blogPostAuthor;
/*System Variables*/
private ListView listView;
private View rootView;
articleListObject object;
public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
listView = (ListView) rootView.findViewById(R.id.article_list);
mProgressBar = (ProgressBar) rootView.findViewById(R.id.progressBarHome);
mTextView = (TextView) rootView.findViewById(R.id.networkCheck);
mTextView.setText("Please Wait while we load the data!");
mProgressBar.setVisibility(View.VISIBLE);
ArticleController articleController = new ArticleController(mListener);
articleController.execute();
return rootView;
}
public MyListener mListener = new MyListener(){
@Override
public void onComplete(JSONArray result)
{
blogPostData = result;
updateArticleList();
mProgressBar.setVisibility(View.INVISIBLE);
mTextView.setVisibility(View.INVISIBLE);
/*List<String> stringList = new ArrayList<String>(Arrays.asList(blogPostTitle));
ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(getActivity(), R.layout.layout_listview_article, R.id.titleTV, stringList);
listView.setAdapter(arrayAdapter1);*/
ArrayList<articleListObject> objects = new ArrayList<articleListObject>();
articleListAdapter articleAdapter = new articleListAdapter(objects);
listView.setAdapter(articleAdapter);
}
};
protected void updateArticleList()
{
try
{
blogPostTitle = new String[blogPostData.length()];
blogPostDate = new String[blogPostData.length()];
blogPostAuthor = new String[blogPostData.length()];
for (int i = 0; i < blogPostData.length(); i++)
{
JSONObject jsonObject = blogPostData.getJSONObject(i);
String title = jsonObject.getString("title");
title = Html.fromHtml(title).toString();
String date = jsonObject.getString("created_at");
date = Html.fromHtml(date).toString();
String author = jsonObject.getString("author");
author = Html.fromHtml(author).toString();
blogPostTitle[i] = title;
blogPostDate[i] = date;
blogPostAuthor[i] = author;
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
}
这是背景异步
public class ArticleController extends AsyncTask<Object, Void, JSONArray> {
MyListener mListener;
public ArticleController(MyListener listenr) {
mListener = listenr;
}
@Override
protected JSONArray doInBackground(Object... arg0)
{
String result = "No data available";
JSONArray jsonResponse = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
//TODO: URL ADDRESS for Articles.
HttpPost httpPost = new HttpPost("http://localhost/****/public/webservices/post");
/*httpPost.setHeader("Content-type", "application/json");*/
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("page", "1"));
nameValuePair.add(new BasicNameValuePair("limit","10"));
nameValuePair.add(new BasicNameValuePair("category","0"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
/*InputStream inputStream = null;*/
HttpResponse response = httpclient.execute(httpPost);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
jsonResponse = new JSONArray(result);
Log.d("RESULT: ", result);
}
catch (MalformedURLException e)
{
Log.e("TAG", "exception caught: ", e);
}
catch (IOException e)
{
Log.e("TAG", "exception caught: ", e);
}
catch (Exception e)
{
Log.e("TAG", "exception caught: ", e);
}
return jsonResponse;
}
@Override
protected void onPostExecute(JSONArray result)
{
HomeFragment homeFragment = new HomeFragment();
homeFragment.blogPostData = result;
mListener.onComplete(result);
}
}
我的CustomAdapter
public class articleListAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<articleListObject> objects;
private class ViewHolder {
TextView textView1;
TextView textView2;
TextView textView3;
}
public articleListAdapter(Context context, ArrayList<articleListObject> objects) {
inflater = LayoutInflater.from(context);
this.objects = objects;
}
public int getCount() {
return objects.size();
}
public articleListObject getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.layout_listview_article, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.titleTV);
holder.textView2 = (TextView) convertView.findViewById(R.id.dateTV);
holder.textView3 = (TextView) convertView.findViewById(R.id.authorTV);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView1.setText(objects.get(position).getPostTitle());
holder.textView2.setText(objects.get(position).getPostDate());
holder.textView3.setText(objects.get(position).getPostAuthor());
return convertView;
}
}
我的构造函数
public class articleListObject {
/*Variables to be displayed*/
protected String postTitle;
protected String postDate;
protected String postAuthor;
public articleListObject(String postTitle, String postDate, String postAuthor) {
this.postTitle = postTitle;
this.postDate = postDate;
this.postAuthor = postAuthor;
}
public String getPostTitle() {
return postTitle;
}
public String getPostDate() {
return postDate;
}
public String getPostAuthor() {
return postAuthor;
}
}