How to make a Custom View(EditText) on the actionb

2019-09-01 15:59发布

问题:

Currently I am making an app that has an EditText on the action bar. I found out how to put a custom view on an actionbar from the following link: How to set a custom view in actionbar in android?. I used the getSupportActionBar to load an EditText onto the action bar.

getSupportActionBar.setCustomView(R.layout.actionbar_view);

It loads an xml file called actionbar_view.xml. The code for that xml file follows below.

    <?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/searchfield"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   android:hint="Search for some app" >

</EditText> 

The problem is that unlike all normal EditTexts placed on the area below an actionbar the edit text on the actionbar is not automatically selected. Is there a way to make this Edit Text on the action bar automatically selected?

By the way, I did take a look at the following link, How to focus and show soft keyboard when a EditText is shown in action bar? Unfortunately I tried to understand the solution and apply to my code but the edit text was still not automatically selected. I am still pretty new to stack overflow, so in case I am not providing enough information/code to solve my problem please tell me in the comments. Thank you!

回答1:

Oh, so after doing some research I found a method called request focus. Request Focus will request focus for the editText, BUT I also needed to add two more lines of code. These two lines of code will pop up the keyboard when the editText is selected. Problem solved! Below is how I requested focus for an edit text on an actionbar.

searchq.requestFocus();
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(searchq, InputMethodManager.SHOW_IMPLICIT);


回答2:

Well there is an alternative to make a custom view as you want .. You don't have to do it in the ActionBar You can Just Hide The ActionBar and make your own view In the xml because you might face some limitiations when using in actionbar.. Hope it might help...