0

在我的应用程序中,我有两种情况需要刷新 ListView (customersList):

1)搜索客户时,我必须在 SearchView 中处理建议项点击

2)当我想显示在另一个活动中创建的新客户时

我有负责刷新 ListView 的单一方法:

private void showCustomer(Integer customerId) {

    ListView customersList = (ListView) findViewById(id.list);

    if(customersList != null) {
      Integer listId = getItemPositionByAdapterId(customersList.getAdapter(), customerId);
      customersList.performItemClick(
        customersList.getAdapter().getView(listId, null, null), 
        listId,
        customersList.getAdapter().getItemId(listId)
      );
      customersList.requestFocusFromTouch();
      customersList.setSelection(listId);
    }
}

private int getItemPositionByAdapterId(ListAdapter adapter, final long id)
{
    for (int i = 0; i < adapter.getCount(); i++)
    {
        if (adapter.getItemId(i) == id)
            return i;
    }
    return -1;
}

showCustomer() 方法在两个地方被调用:

/**
 * Scenario 1: Handle suggestions item click
 */
@Override
protected void onNewIntent(Intent intent) {
  if (Intent.ACTION_VIEW.equals(intent.getAction())) 
    Uri data = intent.getData();
    String customerIdString = data.getLastPathSegment();
    Integer customerId = Integer.parseInt(customerIdString);

    if (customerId != null) {
      showCustomer(customerId);
    }
  }
  super.onNewIntent(intent);
}

/**
 * Scenario 2: Handle new customer creation
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);

  // Check which request we're responding to
  switch (requestCode) {
    case RESULT_CUSTOMER_ADD:
      // Make sure the request was successful
      if (resultCode == RESULT_OK) {
        Integer customerId = data.getIntExtra(MyContract.CustomersEntry._ID, 0);
        // This one doesn't work as expected!
        showCustomer(customerId);
      }
    break;
  }
}

从 onNewIntent() 调用(建议单击项目)时,一切正常 - 项目被选中,列表滚动到项目。

从 onActivityResult() 调用时,该项目被选中,但列表不会滚动到适当的元素。

我没主意了。为什么在这两种情况下它的工作方式不同?任何帮助将不胜感激。

4

1 回答 1

0

你能试试:showCustomer方法中的smoothScrollToPostion(listId)而不是requestFocusFromTouch()吗?我现在无法尝试,所以我将等待您的回复。

于 2013-10-08T14:55:25.330 回答