我对OnItemClickListener有困难。当我还有一个OnScrollListener时,不会调用onItemClick。我将问题缩小到:
public void onScroll(AbsListView absListView, int firstVisible, int visibleCount, int totalCount)
如果在此过程中我调用adapter.notifyDataSetChanged(),则OnItemClickListener不起作用。 任何人有什么建议,或如何解决这个问题? 我在onScroll和onScrollStateChanged都有断点,但似乎没有触及它们。
public class ArticleListActivity extends Activity implements AdapterView.OnItemClickListener, AbsListView.OnScrollListener {
private long categoryId = 0;
private List<Article> objects;
private ArticleListAdapter adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article_list);
Bundle extras = getIntent().getExtras();
if(extras != null){
if(extras.containsKey("categoryId")) categoryId = extras.getLong("categoryId");
}
ListView lv = (ListView) findViewById(R.id.article_list_activity);
iDomsAndroidApp app = ((iDomsAndroidApp) getApplicationContext());
try {
objects = app.getDataManager().getArticlesForCategory(categoryId, 15);
adapter = new ArticleListAdapter(this, R.layout.article_list_cell, objects, categoryId);
lv.setOnScrollListener(this);
lv.setOnItemClickListener(this);
lv.setAdapter(adapter);
} catch (Exception e){
Log.e(iDomsAndroidApp.TAG, "Error " + e.getMessage(), e);
}
}
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), objects.get(position).getTitle(),
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(view.getContext(), ArticleActivity.class);
intent.putExtra("articleId", objects.get(position).getId());
startActivity(intent);
}
public void onScrollStateChanged(AbsListView absListView, int i) {
}
public void onScroll(AbsListView absListView, int firstVisible, int visibleCount, int totalCount) {
if(totalCount == 0) return;
// For the moment only add, not remove items out of view. Buffer of 5.
int buffer = 5;
if(adapter.getCount() + buffer < firstVisible + visibleCount){
Log.d(iDomsAndroidApp.TAG, adapter.getCount() + " + " + buffer + " < " + firstVisible + visibleCount);
// Get next set
try {
iDomsAndroidApp app = ((iDomsAndroidApp) adapter.getContext().getApplicationContext());
List<Article> newObjects = app.getDataManager().getArticlesForCategory(categoryId, adapter.getCount(), totalCount + buffer - adapter.getCount());
for(Article item : newObjects){
adapter.add(item);
}
} catch (Exception e){
Log.e(iDomsAndroidApp.TAG, "Error " + e.getMessage(), e);
}
}
adapter.notifyDataSetChanged();
}
}
答案 0 :(得分:0)
我不知道原因,但是我通过将adapter.notifyDataSetChanged()移动到更新循环(以及其他一些性能增强)来解决了这个问题。性能方面,无论如何这都是有意义的,否则它将被视图的每次移动调用,这是不必要的。这解决了这个问题。