SearchView edittext is always null

后端 未结 3 1919
小鲜肉
小鲜肉 2020-12-16 01:30

I always get that textView is null when doing this:

public boolean onCreateOptionsMenu(Menu menu) {

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

          


        
相关标签:
3条回答
  • 2020-12-16 02:02

    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.

    0 讨论(0)
  • 2020-12-16 02:04

    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.

    0 讨论(0)
  • 2020-12-16 02:24

    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
            }
    
    0 讨论(0)
提交回复
热议问题