java - 从简单列表适配器到自定义 array 适配器

  显示原文与译文双语对照的内容

我有一个来自数据库的retrives数据,并使用简单的适配器在listview中显示它


public class ViewExs extends ListActivity {

//Progress Dialog
private ProgressDialog pDialog;

//Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

//url to get all products list
private static String url_all_products ="http://www.lamia.byethost18.com/get_all_ex.php";

//JSON Node names
private static final String TAG_SUCCESS ="success";
private static final String TAG_PRODUCTS ="products";
private static final String TAG_PID ="ID_exercise";
private static final String TAG_NAME ="ID_exercise";

//products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_view_exs);

//Hashmap for ListView
 productsList = new ArrayList<HashMap<String, String>>();

//Loading products in Background Thread
 new LoadAllProducts().execute();

//Get listview
 ListView lv = getListView();

//on seleting single product
//launching Edit Product Screen
 lv.setOnItemClickListener(new OnItemClickListener() {

 @Override
 public void onItemClick(AdapterView<?> parent, View view,
 int position, long id) {
 Intent i = new Intent(getApplicationContext(), EditProductActivity.class);
 startActivity(i);

/*//getting values from selected ListItem
 String pid = ((TextView) view.findViewById(R.id.pid)).getText()
. toString();

//Starting new intent
 Intent in = new Intent(getApplicationContext(),
 EditProductActivity.class);
//sending pid to next activity
 in.putExtra(TAG_PID, pid);

//starting new activity and expecting some response back
 startActivityForResult(in, 100);*/
 }
 });

}

//Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 super.onActivityResult(requestCode, resultCode, data);
//if result code 100
 if (resultCode == 100) {
//if result code 100 is received 
//means user edited/deleted product
//reload this screen again
 Intent intent = getIntent();
 finish();
 startActivity(intent);
 }

}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

/**
 * Before starting background thread Show Progress Dialog
 * */
 @Override
 protected void onPreExecute() {
 super.onPreExecute();
 pDialog = new ProgressDialog(ViewExs.this);
 pDialog.setMessage("Loading products. Please wait...");
 pDialog.setIndeterminate(false);
 pDialog.setCancelable(false);
 pDialog.show();
 }

/**
 * getting All products from url
 * */
 protected String doInBackground(String... args) {
//Building Parameters
 List<NameValuePair> params = new ArrayList<NameValuePair>();
//getting JSON string from URL
 JSONObject json = jParser.makeHttpRequest(url_all_products,"GET", params);

//Check your log cat for JSON reponse
 Log.d("All Products:", json.toString());

 try {
//Checking for SUCCESS TAG
 int success = json.getInt(TAG_SUCCESS);

 if (success == 1) {
//products found
//Getting Array of Products
 products = json.getJSONArray(TAG_PRODUCTS);

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

//Storing each json item in variable
 String id = c.getString(TAG_PID);
 String name = c.getString(TAG_NAME);

//creating new HashMap
 HashMap<String, String> map = new HashMap<String, String>();

//adding each child node to HashMap key => value
 map.put(TAG_PID, id);
 map.put(TAG_NAME, name);

//adding HashList to ArrayList
 productsList.add(map);
 }
 } else {
//no products found
//Launch Add New product Activity
 Intent i = new Intent(getApplicationContext(),
 NewProductActivity.class);
//Closing all previous activities
 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 startActivity(i);
 }
 } catch (JSONException e) {
 e.printStackTrace();
 }

 return null;
 }

/**
 * After completing background task Dismiss the progress dialog
 * **/
 protected void onPostExecute(String file_url) {
//dismiss the dialog after getting all products
 pDialog.dismiss();
//updating UI from Background Thread
 runOnUiThread(new Runnable() {
 public void run() {
/**
 * Updating parsed JSON data into ListView
 * */
 ListAdapter adapter = new SimpleAdapter(
 ViewExs.this, productsList,
 R.layout.item_list_3, new String[] {TAG_NAME},
 new int[] { R.id.pid});
//updating listview
 setListAdapter(adapter);
 }
 });

 }

}
}

我想使用自定义适配器而不是简单适配器。 这是我的自定义适配器


 public class MySimpleArrayAdapter extends ArrayAdapter<String> {
 private final Context context;
 private final String[] values;
 TextView textView;

 public MySimpleArrayAdapter(Context context, String[] values) {
 super(context, R.layout.item_list_3, values);
 this.context = context;
 this.values = values;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
 LayoutInflater inflater = (LayoutInflater) context
. getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 View rowView = inflater.inflate(R.layout.item_list_3, parent, false);

 final TextView textView = (TextView) rowView.findViewById(R.id.pid);
textView.setText(values[position]);

return rowView;
 }
 } 

我如何做这部分代码


 ListAdapter adapter = new SimpleAdapter(
 ViewExs.this, productsList,
 R.layout.item_list_3, new String[] {TAG_NAME},
 new int[] { R.id.pid});
//updating listview
 setListAdapter(adapter);

在自定义适配器中?

请有人帮忙?

时间: 原作者:

只需在方法中使用 MySimpleArrayAdapter 并设置适配器-


protected void onPostExecute(String file_url) {
//dismiss the dialog after getting all products
 pDialog.dismiss();
//updating UI from Background Thread
 runOnUiThread(new Runnable() 
 {
 public void run() 
 {
/**
 * Updating parsed JSON data into ListView
 * */
 MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(ViewExs.this, 
 new String[] {TAG_NAME});

//updating listview
 setListAdapter(adapter);
 }
 });

 }

原作者:

假设你的值数组是字符串 [] 值,那么


 MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(
 ViewExs.this,values);
 setListAdapter(adapter);

原作者:

我使用了一个自定义 array 适配器,如下所示,它只是一个示例。 但我希望它能帮助。 它显示了使用 fragment 中的ArrayList发送的数据,其中显示了它。


public class MovieAdapter extends ArrayAdapter<Movie> {
 private Context context;
 private List<Movie> movies;

 public MovieAdapter(Context context, List<Movie> movies) {
 super(context, R.layout.movie_layout, movies);
 this.context = context;
 this.movies = movies;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
 View movieView = convertView;

 if (movieView == null) {
 LayoutInflater inflater = (LayoutInflater) context
. getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 movieView = inflater.inflate(R.layout.movie_layout, parent, false);
 }
 movieView.setTag(movies.get(position));
 TextView txtTitle = (TextView) movieView.findViewById(R.id.txtTitle);
 TextView txtDate = (TextView) movieView.findViewById(R.id.txtDate);
 RatingBar ratingBar = (RatingBar) movieView
. findViewById(R.id.ratingBar);
 txtTitle.setText(movies.get(position).MovieTitle);
 txtDate.setText("Date Viewed:" + movies.get(position).dateViewed);
 ratingBar.setIsIndicator(true);
 ratingBar.setNumStars(movies.get(position).rating);
 ratingBar.setRating(movies.get(position).rating);
 return movieView;
 }
}

fragment


public class MyListFragment extends Fragment {

 Movie movie;
 MovieAdapter adapter;
 MovieSelectedListener callBack;

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

 ListView movieList = (ListView) view.findViewById(R.id.movieList);

 movieList.setOnItemClickListener(new OnItemClickListener() {

 @Override
 public void onItemClick(AdapterView<?> parent, View view,
 int position, long id) {
//TODO Auto-generated method stub
 TextView movie = (TextView) view.findViewById(R.id.txtTitle);
 String title = movie.getText().toString();
 callBack.onMovieSelected(title);
 }
 });

 if (getArguments()!= null)
 movie = (Movie) getArguments().getSerializable("Movie");
 Log.v("PASSED","Got here");
 adapter = new MovieAdapter(getActivity(), movie.movies);
 movieList.setAdapter(adapter);
 movieList.setLongClickable(true);
 movieList.setOnItemLongClickListener(new OnItemLongClickListener() {

 @Override
 public boolean onItemLongClick(AdapterView<?> parent,
 final View view, int position, long id) {
//TODO Auto-generated method stub
 AlertDialog.Builder dialog = new AlertDialog.Builder(
 getActivity());
 dialog.setMessage("Are you sure you want to delete this movie?");
 dialog.setTitle("Alert Message");
 dialog.setCancelable(false);
 dialog.setPositiveButton("Yes",
 new DialogInterface.OnClickListener() {

 public void onClick(DialogInterface dialog,
 int which) {
//TODO Auto-generated method stub
 TextView movie = (TextView) view
. findViewById(R.id.txtTitle);
 String title = movie.getText().toString();
 callBack.onDeleteSelected(title, adapter);

 }
 });
 dialog.setNegativeButton("No",
 new DialogInterface.OnClickListener() {

 public void onClick(DialogInterface dialog,
 int which) {
//TODO Auto-generated method stub
 }
 });
 dialog.show();
 return false;
 }
 });
 return view;
 }

 public interface MovieSelectedListener {
 public void onMovieSelected(String movie);

 public void onDeleteSelected(String movie, MovieAdapter adapter);
 }

 @Override
 public void onAttach(Activity activity) {
 super.onAttach(activity);
 ;
 try {
 callBack = (MovieSelectedListener) activity;
 } catch (ClassCastException e) {
 throw new ClassCastException(activity.toString()
 +" must implement MovieSelectedListener");
 }
 }

 public void sortTitle() {

 adapter.sort(new Comparator<Movie>() {
 public int compare(Movie lhs, Movie rhs) {
 return lhs.MovieTitle.compareTo(rhs.MovieTitle);
 }
 });
 adapter.notifyDataSetChanged();
 }

 public void sortDateViewed() {

 adapter.sort(new Comparator<Movie>() {
 public int compare(Movie lhs, Movie rhs) {
 return lhs.dateViewed.compareTo(rhs.dateViewed);
 }
 });
 adapter.notifyDataSetChanged();
 }

 public void sortRating() {

 adapter.sort(new Comparator<Movie>() {
 public int compare(Movie lhs, Movie rhs) {
 return ((Integer) lhs.rating).compareTo(rhs.rating);
 }
 });
 adapter.notifyDataSetChanged();
 }
}

原作者:
...