Edit Text Won't Inflate In The Action Bar
Solution 1:
Try to cast the MenuItem
with its class ((MenuItem)
), use findItem
method and use an inflated View
to retrieve the EditText
as follows:
// cast the menu itemMenuItemmi= (MenuItem) menu.findItem(R.id.item2);
// Use an inflated viewViewview= (View) MenuItemCompat.getActionView(mi);
// Retrieve the edittextEditTextet= (EditText) view.findViewById(R.id.editText1);
In the short way, as your code, it might be resumed by this following code:
MenuItemmi= (MenuItem) menu.getItem(R.id.item2);
EditTextet= (EditText) ( (View) MenuItemCompat.getActionView(mi) ).findViewById(R.id.editText1);
Make sure you return true
in onCreateOptionsMenu
instead of super
method.
Finally, make also sure the item uses a custom prefix like this:
<menuxmlns:android="http://schemas.android.com/apk/res/android"xmlns:customapp="http://schemas.android.com/apk/res-auto" ><itemandroid:id="@+id/item2"customapp:showAsAction="always|collapseActionView"customapp:actionLayout="@layout/layout_edittext"... /></menu>
Solution 2:
- Add android support v7 appcompat library project to your Project.
- Update value for attribute theme as android:theme="@style/Theme.AppCompat.Light" in your activity's entry in manifest file.
Create a layout resource for your custom action bar as
custom_action_bar.xml
<EditText android:id="@+id/test_edit" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Please enter text here !" android:gravity="center_vertical" android:padding="5dp" android:inputType="text" />
Your activity will now be extending ActionBarActivity instead of Activity.
In onCreate() of your activity after super() call, add the following code lines :
View actionBarLayout = getLayoutInflater().inflate(R.layout.action_bar_layout, null);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true); actionBar.setCustomView(actionBarLayout); EditTexteditText= (EditText) actionBarLayout.findViewById(R.id.test_edit); editText.setOnEditorActionListener(newOnEditorActionListener() { @OverridepublicbooleanonEditorAction(TextView v, int actionId, KeyEvent event) { // TODO Auto-generated method stub Log.e("TAG", "key action"); returnfalse; } });
Alternative, instead you can try adding action views http://developer.android.com/guide/topics/ui/actionbar.html#ActionView
Post a Comment for "Edit Text Won't Inflate In The Action Bar"