如何从android中的onSuggestionClick(int position)中的位置获取值

时间:2015-06-17 09:16:51

标签: android

我想从onSuggestionClick(int position)中的position参数获取值。对应于每个选择,在该方法中传递位置。如何从位置获取字符串值?

方法是:

 public boolean onSuggestionClick(int position)
            {
                // Your code here
            String selectedItem = (String)mAdapter.getItem(position);
            Toast.makeText(getBaseContext()," on suggestion click position and item is" + position + selectedItem, Toast.LENGTH_LONG).show();


                startActivity(new Intent(getBaseContext(), SearchResultsActivity.class));

                return true;
            }

相应的适配器是:

final String[] from = new String[] {"cityName"};
        final int[] to = new int[] {android.R.id.text1};
        mAdapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_2,
                null,
                from,
                to,
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        search.setSuggestionsAdapter(mAdapter);

我收到以下错误:

  

java.io.IOException的               在android.accounts.AccountManager.convertErrorToException

1 个答案:

答案 0 :(得分:1)

position 参数返回所显示建议列表中所点击项目的绝对位置。

mAdapterSimpleCursorAdapter

的对象
public SimpleCursorAdapter mAdapter;

下面的代码是获取点击建议的文本值

SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
searchView.setIconifiedByDefault(false);
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setSuggestionsAdapter(mAdapter);
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
    @Override
    public boolean onSuggestionClick(int position) {
        Cursor cursor = mAdapter.getCursor();
        cursor.moveToPosition( position );
        columnIndex = 1 /* Set your column index*/
        String selectedItem = cursor.getString(columnIndex);
        Log.d("Clicked Item", selectedItem);
        return true;
    }

    @Override
    public boolean onSuggestionSelect(int position) {
        /* Write your code */
        return true;
    }
});

logcat的: LogCat Print

搜索用户界面: Search UI