Android onCreateOptionMenu not being called - java

I am implementing an Android Activity from which other Activities will be derived from. So basically I have this setup of an InventoryActivity and its parent class, ListActivity:
public class MyListActivity extends Activity {
protected Context mContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this.getBaseContext();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options, menu);
Log.d("Creating options menu", "True");
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
Log.d("Preparing options menu", "True");
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
return(true);
case R.id.revert:
return(true);
}
return(super.onOptionsItemSelected(item));
}
}
public class InventoryActivity extends MyListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inventory);
}
}
And I also have this in options.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/card_list_save"
android:icon="#drawable/ic_menu_save"
android:title="Save"/>
<item android:id="#+id/card_list_revert"
android:icon="#drawable/ic_menu_revert"
android:title="Revert" />
</menu>
If necessary, this is my layout for inventory.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/callSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Search"/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/inventory"/>
</ScrollView>
</LinearLayout>
However, when I press the menu button, nothing happens. The Log messages in the onCreateOptionsMenu method does not appear. Instead all I can see is the following:
02-04 11:36:58.313: W/KeyCharacterMap(31464): No keyboard for id 0
02-04 11:36:58.313: W/KeyCharacterMap(31464): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
But what baffles me the most is that this code works in other Activities, such as my launcher Activity. But by the concept of object oriented programming, the InventoryActivity should call the overriding methods in the MyListActivity. I am completely stuck and I need help.

ListActivity is already a class in the Android SDK. My guess is that you're importing android.app.ListActivity, and not your package.

Hmm...don't know why but removing the onCreate method in MyListActivity fixed the problem. So the class now looks like this:
public class MyListActivity extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options, menu);
Log.d("Creating options menu", "True");
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
Log.d("Preparing options menu", "True");
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
return(true);
case R.id.revert:
return(true);
}
return(super.onOptionsItemSelected(item));
}
}

Related

How can I implement the bottom navigation bar into an app for android?

Here is a piece of Java code.
The Android app stops when I tap on an item in the BottomNavigationView, it should open a fragment.
public class MainActivity extends AppCompatActivity {
private BottomNavigationView bottomNavigationView;
private BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths:
switch (item.getItemId()) {
case R.id.item0:
transaction.replace(R.id.content, new Item0_Fragment()).commit();
return true;
case R.id.item1:
transaction.replace(R.id.content, new Item1_Fragment()).commit();
return true;
case R.id.item2:
transaction.replace(R.id.content, new Item2_Fragment()).commit();
return true;
case R.id.item3:
transaction.replace(R.id.content, new Item3_Fragment()).commit();
return true;
}
return false;
}
});
}
First, you did declares two times the BottomNavigationView. In second, you not writed the complete code, leaving aside parts that may be important. However I did write a code for this. Try read my code or just copy and paste. You just need create your fragments, if needs help to do this let me know.
MainActivity.java
public class MainActivity extends AppCompatActivity {
List<Fragment> fragmentList;
MyAdapter myAdapter;
ViewPager viewPager;
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG,"onCreate()");
fragmentList = new ArrayList<>();
fragmentList.add(new Fragment1());
fragmentList.add(new Fragment2());
bottomNavigationView = findViewById(R.id.bottomNavigationView);
viewPager = findViewById(R.id.viewPagerAppActivity);
myAdapter = new MyAdapter(getSupportFragmentManager());
viewPager.setAdapter(myAdapter);
viewPager.setCurrentItem(0);
bottomNavigationView.setOnNavigationItemSelectedListener(botNavViewItemSelectedListener());
}
public BottomNavigationView.OnNavigationItemSelectedListener botNavViewItemSelectedListener() {
return new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.itemFragment1:
viewPager.setCurrentItem(0);
break;
case R.id.itemFragment2:
viewPager.setCurrentItem(1);
break;
}
return true;
}
};
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
}
}
activity_main.xml
<android.support.constraint.ConstraintLayout android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v4.view.ViewPager
android:id="#+id/viewPagerAppActivity"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#id/bottomNavigationView"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginBottom="0dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="0dp"
app:layout_constraintVertical_bias="1.0" />
<android.support.design.widget.BottomNavigationView
app:menu="#menu/menu_bottom"
android:id="#+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:itemBackground="#color/colorPrimary"
app:itemIconTint="#drawable/bottom_bar_item_selector"
app:itemTextColor="#drawable/bottom_bar_item_selector"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>
menu_bottom.xml to populate my menu of navigation
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/itemFragment1" android:title="Frag1" android:enabled="true" app:showAsAction="always|withText" android:icon="#mipmap/ic_launcher"/>
<item android:id="#+id/itemFragment2" android:title="Frag2" android:enabled="true" app:showAsAction="always|withText" android:icon="#mipmap/ic_launcher"/>
</menu>
*For fragment click this http://www.truiton.com/2017/01/android-bottom-navigation-bar-example/
*For activities
Following code makes the bottom navigation for activites(same feel as to fragment)
STEP 1: Create a BaseActivity and name it as BaseActivity
BaseActivity.java
public abstract class BaseActivity extends AppCompatActivity implements
BottomNavigationView.OnNavigationItemSelectedListener{
protected BottomNavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewId());
navigationView = findViewById(R.id.navigation);
navigationView.setOnNavigationItemSelectedListener(this);
BottomNavigationViewHelper.disableShiftMode(navigationView);
}
#Override
protected void onStart() {
super.onStart();
updateNavigationBarState();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menuBuilding) {
startActivity(new Intent(this, ActivityA.class));
} else if (itemId == R.id.menuChat) {
startActivity(new Intent(this, ActivityB.class));
} else if (itemId == R.id.menuProfile) {
startActivity(new Intent(this, ActivityC.class));
}
overridePendingTransition(0, 0);
finish();
return true;
}
private void updateNavigationBarState() {
int actionId = getNavigationMenuItemId();
selectBottomNavigationBarItem(actionId);
}
void selectBottomNavigationBarItem(int itemId) {
Menu menu = navigationView.getMenu();
for (int i = 0, size = menu.size(); i < size; i++) {
MenuItem item = menu.getItem(i);
boolean shouldBeChecked = item.getItemId() == itemId;
if (shouldBeChecked) {
item.setChecked(true);
break;
}
}
}
abstract int getContentViewId();
abstract int getNavigationMenuItemId();
}
STEP 2:
Create a child activity and name it as ActivityA and copy paste the following code
ActivityA.java
public class ActivityA extends BaseActivity implements {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
int getContentViewId() {
return R.layout.activity_a_layout;
}
#Override
int getNavigationMenuItemId() {
return R.id.menuBuilding;
}
}
Similary create ActivityB.java and ActivityC.java .Make both classes similar to ActivityA.java.But the different is ActivityA.java returns
#Override
int getNavigationMenuItemId() {
return R.id.menuBuilding;
}
and
ActivityB.java returns
#Override
int getNavigationMenuItemId() {
return R.id.menuChat;
}
and
ActivityC.java returns`
#Override
int getNavigationMenuItemId() {
return R.id.menuProfile;
}
Also create layout for two java class and copy paste the activity_a_layout.xml code to both layouts of ActivityB.java and ActivityC.java
STEP 3 : Create a layout named activity_a_layout and copy paste the following code
'activity_a_layout.xml'
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar"
android:background="#android:color/white">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Coming soon..."
android:textSize="19sp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
</RelativeLayout>
<include
android:id="#+id/navigation"
layout="#layout/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
STEP 4:
Create a layout named bottom_navigation and copy pase the following code
bottom_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.BottomNavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/dark_grey"
app:itemIconTint="#drawable/nav_item_menu_selector"
app:itemTextColor="#drawable/nav_item_menu_selector"
app:menu="#menu/bottom_nav_items" />
STEP 5: Create a menu folder inside res and create a file named bottom_nav_items inside menu and copy paste the below code
bottom_nav_items.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menuChat"
android:icon="#drawable/ic_chat"
android:title="Chat" />
<item
android:id="#+id/menuBuilding"
android:icon="#drawable/ic_building_white"
android:title="Company" />
<item
android:id="#+id/menuProfile"
android:icon="#drawable/menu_item_profile"
android:title="Profile"
app:itemTextColor="#android:color/transparent" />
</menu>
**Dont forgot to declare ActivityA.java,ActivityB.java and ActivityC.java in manifest
HAPPY CODING

My menu_main.xml do not show on my main_activity

I just a newbie in android programming, i am building a new app from a tutorial.
I have make the main menu like this
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="id.go.kemenkeu.itjen_kemenkeu.MainActivity">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
app:showAsAction="never"
android:title="Settings" />
<item
android:id="#+id/navigate"
android:title="#string/next"
android:orderInCategory="200"
app:showAsAction="always"
android:icon="#drawable/ic_next"/> </menu>
and the MainActivity.Java like this
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar= (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==R.id.action_settings){
Toast.makeText(this,"Hi, Anda Baru Saja Menekan"+item.getTitle(),Toast.LENGTH_SHORT).show();
return true;
}
if(id==R.id.navigate){
startActivity(new Intent(this, SubActivity.class));
}
return super.onOptionsItemSelected(item);
} }
I call the +id/navigate in MainActivity.Java, but when i run in emulator, the style inside +id/navigate didn't show. What is wrong here?
you have to override createoptionmenu for intialize your own menu in toolbar.
try adding this in you activity:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mymenu_main, menu);
return super.onCreateOptionsMenu(menu);
}
without onCreateOptionsMenu you cant show menu. so add onCreateOptionsMenu to your Activity Class like,
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
Happy Coding!!!
You must inflate the option menu
Add this line.
getMenuInflater().inflate(R.menu.main, menu);
You have to override the onCreateOptionsMenu in you Activity and inflate the menu and check it
more details you have to check in Developer Site

Handling click event of switch widget on action bar

This is how I added a switch widget to the action bar. I'm already playing with it. But I'm not knowing how to respond to the click events.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
System.out.println("actionbar clicked");
// Handle item selection
if (item.getItemId()==R.id.myswitch) {
Switch actionView = (Switch)item.getActionView();
actionView.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
status = isChecked;
System.out.println(status);
}
});
return true;
}
return super.onOptionsItemSelected(item);
}
This is my switch layout and map resource file
switch_status.xml
<?xml version="1.0" encoding="utf-8"?>
<Switch
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:showText="true"
android:textOff="Free"
android:textOn="Booked" />
map.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="#+id/myswitch"
android:showAsAction="always"
android:title=""
android:actionLayout="#layout/switch_status" />
</menu>
While clicking the switch, It is changing its state, but I cannot see even one msg on the console like "actionbar clicked" & "true" / "false". And there is no error either.
I'm not sure weather this is the correct way of handling clicks on actionbar. If any one can help me with this code, it will be really nice.
Thankyou
Best way for do this using Toolbar .
In Toolbar you can add any view and control this.
You don't need to set a OnCheckedChangeListener, onOptionsItemSelected is a "onClickListener"
use switch for this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
System.out.println("actionbar clicked");
// Handle item selection
switch (item.getItemId()) {
case R.id.myswitch:
System.out.println(((Switch)item.getActionView()).isChecked());
break;
}
return super.onOptionsItemSelected(item);
}
I had the same issue and achieved by following below technique
Added onClick method for switch like below
<Switch
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:showText="true"
android:textOff="Free"
android:textOn="Booked"
android:onClick="onSwitch"
/>
Implement onSwitch method in Activity as below:
public void onSwitch(View view) {
Switch androidSwitch = findViewById(R.id.switch1);
if(androidSwitch.isChecked()){
Log.i("Test","enabled");
}else{
Log.i("Test","disabled");
}
}

invalidateOptionsMenu() not working when "restarting" activity

I have an activity, let's call it FirstActivity.java, which has an actionBar with a navigation drawer instantiated via fragment. In this fragment, NavigationDrawerFragment.java, I've put the methods onCreateOptionsMenu(Menu menu, MenuInflater inflater), onOptionsItemSelected(MenuItem item) and onPrepareOptionsMenu(Menu menu) as anyone normally would in order to instantiate the actionBar. On the right side of the actionBar, I have a button with a "messages" icon that leads to the user's inbox fragment. When a new message incomes, I call invalidateOptionsMenu() inside my FirstActivity and change the icon to a brighter one in onPrepareOptionsMenu(Menu menu). Everything works fine so far.
The problem is: I can leave the FirstAcitivty via one of the options in the navigation drawer. I do it via Intent. Let's call it SecondActivity.java.
Intent myIntent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(myIntent);
finish();
When I call the FirstAcitivity again, also via Intent, the invalidateOptionsMenu() method stops working. It does not trigger the methods onCreateOptionsMenu nor onPrepareOptionsMenu. I have also tried supportInvalidateOptionsMenu() with no luck.
Only when I hit the MENU BUTTON (on the left side of the actionBar) is that these methods are called and the messages icon is changed. Does anyone know the reason for this strange behavior?
Better yet, does anyone know a solution for my problem? : )
FirstActivity.java
public class FirstActivity extends ActionBarActivity impements NavigationDrawerFragment.NavigationDrawerCallbacks {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity);
// When a new message arrives
if (thereIsAnIncomingMessage) {
invalidateOptionsMenu();
}
}
}
first_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" android:id="#+id/first_activity_layout">
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FirstActivity">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout android:id="#+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.Controller.Main.NavigationBar.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
NavigationDrawerFragment.java
public class NavigationDrawerFragment extends Fragment {
private RelativeLayout relativeLayout;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
relativeLayout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
return relativeLayout;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_menu) {
// Open navigation drawer menu
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
} else if (item.getItemId == R.id.action_chat) {
// Open messages fragment
MessagesFragment messagesFragment = new MessagesFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, messagesFragment, "MESSAGES_FRAGMENT");
fragmentTransaction.addToBackStack("chatFrag");
fragmentTransaction.commit();
}
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (FirstActivity.thereIsAnIncomingMessage) {
menu.getItem(0).setIcon(R.drawable.new_message_icon);
} else {
menu.getItem(0).setIcon(R.drawable.message_icon);
}
}
public interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
}
}
The problem is that the OnCreate method of FirstActivity is not called when you hit the back button. Instead, you can put your code in OnResume, as follows:
#Override
public void onResume(){
super.onResume();
if(thereIsAnIncomingMessage)
invalidateOptionsMenu();
}
See the official Activity Lifecycle documentation.

NullPointerException in android while using actionLayout in menu.xml

I want to use custom SearchView in menu of my App but I'm encountering a NullPointerException in android while using actionLayout in menu.xml
I have custom layout for menu :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/search_btn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#android:drawable/ic_menu_search"/>
<EditText
android:id="#+id/search_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/search_btn"
android:layout_toLeftOf="#+id/search_btn"
android:ems="10"
android:inputType="none" >
<requestFocus />
</EditText>
and my menu.xml is :
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/search_view"
android:icon="#android:drawable/ic_menu_search"
android:actionLayout="#layout/search_menu"
android:showAsAction="collapseActionView|ifRoom"
android:title="#string/search_title"/>
</menu>
Now I want to add OnClickListener on _search_btn_ So I did that likewise :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
searchButton = (Button) menu.findItem(R.id.search_btn);
searchButton.setOnClickListener(new OnClickListener() { // SEE HERE I'M GETTING NullPointerException
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, ((EditText) findViewById(R.id.search_et)).getText().toString(), Toast.LENGTH_LONG).show();
}
});
return true;
}
but I'm getting my NullPointerException on above mentioned line. How can I add ClickListener to that button???
You're using the wrong id. Use the id for your menu item. You can use getActionView on the MenuItem to get the layout.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.search_view);
Button searchButton = searchItem.getActionView().findViewById(R.id.search_btn);
searchButton.setOnClickListener(new OnClickListener() { // SEE HERE I'M GETTING NullPointerException
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, ((EditText) findViewById(R.id.search_et)).getText().toString(), Toast.LENGTH_LONG).show();
}
});
return true;
}
please try on onOptionsItemSelected method.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.search_view:
//write your code here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Well your not getting a reference to your button. i.e in searchButton = (Button) menu.findItem(R.id.search_btn); you searchButton is null.
Your using a wrong id.

Categories