我正在尝试创建交互式ListView
而不扩展ListActivity
类。布局应该是左边的RatingBar
和右边的标签。这是我到目前为止的代码,它没有任何编译错误,但在启动应用程序时崩溃:
public class ProDroid_BAActivity extends Activity {
private static final String[] items = { "lorem", "ipsum", "dolor", "sit",
"amet", "consectetuer", "adipiscing", "elit", "morbi", "vel",
"ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel",
"erat", "placerat", "ante", "porttitor", "sodales", "pellentesque",
"augue", "purus" };
ListView listv = (ListView) findViewById(R.id.listView1);
ArrayAdapter<RowModel> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<RowModel> list = new ArrayList<RowModel>();
for (String s : items) {
list.add(new RowModel(s));
}
adapter = new RatingAdapter(list);
listv.setAdapter(adapter);
}
private RowModel getModel(int position) {
return adapter.getItem(position);
}
class RatingAdapter extends ArrayAdapter<RowModel> {
public RatingAdapter(ArrayList<RowModel> list) {
super(ProDroid_BAActivity.this, R.layout.row, R.id.label, list);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
ViewHolder holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
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());
}
};
holder.rate.setOnRatingBarChangeListener(l);
}
RowModel model = getModel(position);
holder.rate.setTag(new Integer(position));
// holder.text.setTag(new Integer(position));
holder.rate.setRating(model.rating);
// holder.text.setText(model.label);
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);
}
}
}
答案 0 :(得分:3)
移动线:
ListView listv = (ListView) findViewById(R.id.listView1);
设置内容视图后,在onCreate()
方法中。