setListAdapter(new CheckAdapter (this, list));

  selection = (TextView)findViewById(R.id.selection);

 }

 private RowModel getModel(int position) {

  return(((CheckAdapter)getListAdapter ()).getItem(position));

 }

 public void onListItemClick(ListView parent, View v,

  int position, long id) {

  selection.setText(getModel (position).toString());

 }

 class CheckAdapter extends ArrayAdapter<RowModel> {

  Activity context;

  CheckAdapter(Activity context, ArrayList<RowModel> list) {

   super(context, R.layout.row, list);

   this.context = context;

  }

  public View getView(int position, View convertView,

   ViewGroup parent) {

   View row = convertView;

   ViewWrapper wrapper;

   RatingBar rate;

   if (row==null) {

    LayoutInflater inflater = context.getLayoutInflater();

    row = inflater.inflate(R.layout.row, null);

    wrapper = new ViewWrapper(row);

    row.setTag(wrapper);

    rate = wrapper.getRatingBar();

    RatingBar.OnRatingBarChangeListener l =

     new RatingBar.OnRatingBarChangeListener() {

     public void onRatingChanged(RatingBar ratingBar,

      float rating, boolean fromTouch) {

      Integer myPosition = (Integer)ratingBar.getTag();

      RowModel model = getModel(myPosition);

      model.rating = rating;

      LinearLayout parent = (LinearLayout)ratingBar.getParent();

      TextView label = (TextView)parent.findViewById(R.id.label);

      label.setText(model.toString());

     }

    };

    rate.setOnRatingBarChangeListener(l);

   } else {

    wrapper = (ViewWrapper)row.getTag();

    rate = wrapper.getRatingBar();

   }

   RowModel model = getModel(position);

   wrapper.getLabel().setText (model.toString());

   rate.setTag(new Integer(position));

   rate.setRating(model.rating);

   return(row);

  }

 }

 class RowModel {

  String label;

  float rating = 2.0f;

  RowModel(String label) {

   this.label = label;

  }

  public String toString() {

   if (rating>=3.0) {

    return (label.toUpperCase());

   }

   return(label);

  }

 }

}

Here is what is different between our earlier code and this activity and getView() implementation:

• While we are still using String[] items as the list of nonsense words, but rather than pouring that String array straight into an ArrayAdapter, we turn it into a list of RowModel objects. RowModel is this demo’s poor excuse for a mutable model; it holds the nonsense word plus the current checked state. In a real system, these might be objects populated from a Cursor, and the properties would have more business meaning.

• Utility methods like onListItemClick() had to be updated to reflect the change from a pure

Вы читаете Beginning Android
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату