У меня есть Activity
, которое извлекает данные из веб-службы. Эти данные представлены в ListView
через ArrayAdapter, который заполняет RelativeLayout
тремя TextView
внутри, ничего особенного, и все работает нормально.
Теперь я хочу. реализовать действие Details Activity
, которое должно вызываться, когда пользователь щелкает элемент в ListView, звучит легко, но я не могу на всю жизнь заставить onItemClickListener работать с моим ArrayAdapter.
Это моя основная Activity
:
public class Schema extends Activity {
private ArrayList lessons = new ArrayList();
private static final String TAG = "Schema";
ListView lstLessons;
Integer lessonId;
// called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// can we use the custom titlebar?
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
// set the view
setContentView(R.layout.main);
// set the title
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
// listview called lstLessons
lstLessons = (ListView)findViewById(R.id.lstLessons);
// load the schema
new loadSchema().execute();
// set the click listeners
lstLessons.setOnItemClickListener(selectLesson);
}// onCreate
// declare an OnItemClickListener for the AdapterArray (this doesn't work)
private OnItemClickListener selectLesson = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View v, int i, long l) {
Log.v(TAG, "onItemClick fired!");
}
};
private class loadSchema extends AsyncTask {
private ProgressDialog progressDialog;
// ui calling possible
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Schema.this,"", "Please wait...", true);
}
// no ui from this one
@Override
protected Void doInBackground(Void... arg0) {
// get some JSON, this works fine
}
@Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
// apply to list adapter
lstLessons.setAdapter(new LessonListAdapter(Schema.this, R.layout.list_item, lessons));
}
Мой код ArrayAdapter:
// custom ArrayAdapter for Lessons
private class LessonListAdapter extends ArrayAdapter {
private ArrayList lessons;
public LessonListAdapter(Context context, int textViewResourceId, ArrayList items) {
super(context, textViewResourceId, items);
this.lessons = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
Lesson o = lessons.get(position);
TextView tt = (TextView) v.findViewById(R.id.titletext);
TextView bt = (TextView) v.findViewById(R.id.timestarttext);
TextView rt = (TextView) v.findViewById(R.id.roomtext);
v.setClickable(true);
v.setFocusable(true);
tt.setText(o.title);
bt.setText(o.fmt_time_start);
rt.setText(o.room);
return v;
}
}// LessonListAdapter
The main.xml
The list_item.xml
Возился с этим последние пару часов и Кажется, я не могу понять, в чем проблема. Моя проблема очень похожа на этот вопрос , но я не расширяю ListActivity, поэтому я до сих пор не знаю, куда должен идти мой onListClickItem ().
ОБНОВЛЕНИЕ: Теперь у меня есть ломал голову над этим несколько дней и все никак не мог найти проблему.
Следует ли мне переписать действие, на этот раз расширив ListActivity вместо Activity? Потому что он предоставляет сам метод onItemClick и, вероятно, его легче перезаписать.
Или, должен ли я привязать слушателя непосредственно к каждому getView () в моем ArrayAdapter? Я считаю, что прочитал, что это плохая практика (я должен делать то, что пытался и потерпел неудачу в своем сообщении).