11

I always get that textView is null when doing this:

public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);

        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) MenuItemCompat
                .getActionView(searchItem);

        int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
        TextView textView = (TextView) searchView.findViewById(id);
        textView.setTextColor(Color.WHITE);
}

Anyone know why?

danielrvt-sgb
  • 1,088
  • 5
  • 16
  • 33

3 Answers3

36

I'm using action bar of appcompat v7 and my solusion is:

TextView searchText = (TextView) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);

Hope this help.

Penicylline
  • 442
  • 4
  • 2
19

It's a EditText not a TextView.

Try something like that:

int id = searchView.getContext()
                   .getResources()
                   .getIdentifier("android:id/search_src_text", null, null);
EditText editText = (EditText) searchView.findViewById(id);

Hope it helps.

Mohammed Aouf Zouag
  • 16,366
  • 3
  • 36
  • 64
Undisputed
  • 271
  • 1
  • 7
  • 2
    An EditText is a TextView, actually. It inherits TextView. That's why they have a lot of the same methods. EditText is just editable. – afollestad Apr 08 '15 at 00:08
  • @afollestad You´re right. But in my case it has worked with an EditView but not with a TextView. I dont know exactly why. Maybe one of the magical android mysteries again. – Undisputed Apr 23 '15 at 11:52
  • 1
    Been searching for HOURS until I found this buried here. Just wanted to thank you so much – Justin Nov 25 '19 at 06:21
1

If you are using AndroidX then you can do like this in kotlin.

override fun onCreateOptionsMenu(menu: Menu): Boolean {
            // Inflate the menu; this adds items to the action bar if it is present.
            menuInflater.inflate(R.menu.main, menu)
            val searchItem: MenuItem = menu.findItem(R.id.action_search)
            val searchView: SearchView = searchItem.actionView as SearchView
            val searchText: TextView = searchView?.findViewById(androidx.appcompat.R.id.search_src_text);
            searchText.setTextColor(Color.BLACK)
            searchText.background = resources.getDrawable(R.drawable.rounded_corner_background)

            return true
        }
Rajiv Ranjan
  • 253
  • 3
  • 12