0

私のアプリでは、ListView (customersList) を更新する必要がある 2 つのシナリオがあります。

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() メソッドは、次の 2 つの場所で呼び出されます。

/**
 * 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