为什么Android的SearchView小部件的ImageView(id = search_mag_icon)返回null?

时间:2015-08-07 09:53:14

标签: android nullpointerexception searchview android-search

默认SearchView在展开时在搜索提示中有一个搜索图标。我想从提示中删除此图标。

enter image description here

所以我看到了this answer on SO。它在onCreate()中提供了以下解决方案:

int magId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
ImageView magImage = (ImageView) searchView.findViewById(magId);
magImage.setLayoutParams(new LinearLayout.LayoutParams(0, 0));

查看xml code of Android's search_view.xml here,此解决方案确实非常有意义,但我在以下代码段的第6行获得了NullPointerException

SearchView searchView = (SearchView) findViewById(R.id.searchActivity_searchView);
        int magId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
        Log.i(TAG, "magId > "+ magId);
        ImageView magImage = (ImageView) searchView.findViewById(magId);
        Log.i(TAG, "magImage > "+ magImage);
        magImage.setLayoutParams(new LinearLayout.LayoutParams(0, 0));

在异常之前,它会打印:

08-07 14:13:15.740: I/SearchActivity(2548): magId > 16909188
08-07 14:13:15.740: I/SearchActivity(2548): magImage > null

那我该怎么办呢?

1 个答案:

答案 0 :(得分:0)

试试这个:

EditText searchEditText = (EditText) searchview.findViewById(android.support.v7.appcompat.R.id.search_src_text);
SpannableStringBuilder ssb = new SpannableStringBuilder("");
ssb.append(hintText);
searchEditText.setHint(ssb);