Search view widget and Icon not showing up in the action bar - android

I am a beginner to Android. Trying to add a search a widget in the action bar.
Here is my menu file code ("main_acitivity.xml"):
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:icon="#drawable/ic_search"
android:title="#string/action_search"
android:showAsAction="always"
android:actionViewClass="android.support.v7.widget.SearchView" />
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:showAsAction="never" />
</menu>
My MainActivity class code is:
package com.example.fragment;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.fragment.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater= getMenuInflater();
inflater.inflate(R.menu.main_activity,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void sendMessage(View view){
Intent intent= new Intent(this,DisplayMessageActivity.class);
EditText editText= (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
I have tried "android.widget.SearchView" as well but it is not even showing the icon. Could you please advise what I am doing wrong ?

you missed these:
xmlns:yourappname="http://schemas.android.com/apk/res-auto"
and
yourappname:showAsAction="always"
yourappname:actionViewClass="android.support.v7.widget.SearchView"/>

Related

Easy share action is not working in WebView Android app

I have been trying almost everything to get this share button to work. The button is placed right but it's not getting clicked and the share window is not showing.
Secondly, I want it to share Web URL of the page when clicked and I am also unable to understand how to do that.
Moreover, I do not want the button to be hidden in the Action settings. I want it to be displayed on the top bar, that's what's my main problem is.
MainActivity.java
package com.yoalfaaz.yoalfaaz;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.support.v4.view.MenuItemCompat;
public class MainActivity extends AppCompatActivity {
private WebView YoWeb;
private ShareActionProvider mShareActionProvider;
SwipeRefreshLayout swipe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb();
}
});
LoadWeb();
}
public void LoadWeb() {
YoWeb = (WebView)findViewById(R.id.webview);
WebSettings webSettings = YoWeb.getSettings();
webSettings.setJavaScriptEnabled(true);
YoWeb.loadUrl("http://www.yoalfaaz.com");
swipe.setRefreshing(true);
YoWeb.setWebViewClient(new WebViewClient() {
//onPageFinished Method
public void onPageFinished(WebView view, String url) {
//Hide the SwipeRefreshLayout
swipe.setRefreshing(false);
}
});
}
#Override
public void onBackPressed() {
if (YoWeb.canGoBack()) {
YoWeb.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.menu_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
private Intent createShareIntent() {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
shareIntent.setType("text/plain");
startActivity(shareIntent);
return shareIntent;
}
}
menu_main.xml
<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="com.yoalfaaz.yoalfaaz.MainActivity">
<item
android:id="#+id/menu_item_share"
android:showAsAction="ifRoom"
android:title="Share"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
app:showAsAction="always" />
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
First, the button is not clickable.
Second, how to share the current page URL?
These are the two queries which I am unable to solve.

Duplicating menu items everytime it open in overflow options menu

I am trying to add two menu items in action bar with xml code:
<?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">
<item
android:id="#+id/search"
android:title="#string/search"
android:icon="#drawable/ic_action_search"
app:showAsAction="ifRoom"
/>
<item
android:id="#+id/share"
android:title="#string/share"
android:icon="#drawable/ic_action_share"
app:showAsAction="ifRoom"
/>
And my java code is :
package com.erprakash.contacts;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
//import android.net.Uri;
import android.provider.ContactsContract;
//import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
//import java.util.Comparator;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<Contact> arrayList = new ArrayList<>();
int img_id = R.drawable.image1;
String name ;
String number ;
private int id;
private Contact contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Tool bar setting
//toolbar end
// Reading Contacts -----Working
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
if (phones != null) {
while (phones.moveToNext())
{
name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
id = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO_FILE_ID));
if(id == 0){
contact = new Contact(number, name, img_id);
}else {
contact = new Contact(number, name, id);
}
arrayList.add(contact);
}
phones.close();
}
/**
name = getResources().getStringArray(R.array.person_name);
number = getResources().getIntArray(R.array.mobile_number);
int c = 0;
for(String Name: name)
{
Contact contact = new Contact(number[c],Name,img_id[c]);
c++;
arrayList.add(contact);
}
**/
recyclerView = (RecyclerView)findViewById(R.id.rvMainContennt);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new ContactAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
//-------------Toolbar------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int res_id = item.getItemId();
if(res_id == R.id.search)
{
Toast.makeText(this.getApplicationContext(),"You have seleted search option",Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public boolean onPrepareOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
}
In preview the design appears correct :
But in running state :
And on clicking the option menu :
Every time when i open the option menu the content gets duplicated and goes on , i have searched solution for this but i didn't get it anywhere . help me out....Thanks in advance
Remove onPrepareOptionsMenu().
#Override
public boolean onPrepareOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
Update onCreateOptionsMenu() as below:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
If you want to show menu item always on Toolbar, then update menu_main.xml as below:
<?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">
<item
android:id="#+id/search"
android:title="#string/search"
android:icon="#drawable/ic_action_search"
app:showAsAction="always" />
<item
android:id="#+id/share"
android:title="#string/share"
android:icon="#drawable/ic_action_share"
app:showAsAction="always" />
</menu>
When I ran into this issue I called menu.clear() inside of onPrepareOptionsMenu and that fixed it.
If your wondering why I didn't switch to onCreateOptionsMenu it is because I need to use onPrepareOptionsMenu for reasons.

ShareActionProvider not doing anything

I have been following the Android Development course on Udacity, and got to a lesson where we were to implement a ShareActionProvider. After attempting it myself, and then following what they did--I'm certain it's not working properly.
I'm putting the code in a Fragment; the correct item is present in the overflow menu, but when I click "Share", nothing happens. I noticed when I open the DetailsActivity, that the following appears in the logs:
17493-17493/com.dummy.sunshine.app W/MenuItemCompat﹕ setActionProvider: item does not implement SupportMenuItem; ignoring
I'm not sure what that means, but I couldn't find anything about it online. I would assume that clicking it is supposed to do something--however, they never go over what's supposed to happen after that lesson--so I'm a tad confused.
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
public class DetailActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
DetailFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A placeholder fragment containing a simple view.
*/
public class DetailFragment extends Fragment {
private static String mForecastStr;
private final String TAG = DetailActivity.class.getSimpleName();
public DetailFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
Intent intent = getActivity().getIntent(); //allows us to get data from the screen that sent us to this activity
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
mForecastStr = intent.getStringExtra(Intent.EXTRA_TEXT); //we get the EXTRA_TEXT that the ForecastFragment sent us
((TextView) rootView.findViewById(R.id.detail_text))
.setText(mForecastStr);
}
return rootView;
}
private Intent shareDetailForecast() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, mForecastStr + "#SunshineApp");
return sendIntent;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.menu_detail_fragment, menu);
MenuItem menuItem = menu.findItem(R.id.action_share);
ShareActionProvider mShareActionProvider = new ShareActionProvider(getActivity());
mShareActionProvider.setShareIntent(shareDetailForecast());
MenuItemCompat.setActionProvider(menuItem, mShareActionProvider);
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareDetailForecast());
} else {
Log.d(TAG, "mShareActionProvider is null...");
}
}
}
menu_detail_fragment.xml
<?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">
<item android:id="#+id/action_share"
android:title="#string/action_share"
android:orderInCategory="5"
app:showAsAction="ifRoom"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />
</menu>
menu_detail.xml
<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="com.nxt3.sunshine.app.DetailActivity">
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
</menu>
This is what the app looks like on the DetailActivity page:
I believe your problem is that on your DetailActivity you are extending a FragmentActivity while you should be extending an AppCompatActivity (which is a subclass of the FragmentActivity), as you are using an action bar on your activity and using the support library.
so you should replace this:
public class DetailActivity extends FragmentActivity {
by this:
public class DetailActivity extends AppCompatActivity {
and import the support library:
import android.support.v7.app.AppCompatActivity;
I don't know if you already have it set, but you also need to set your AppTheme to be Theme.AppCompat or something similar on your AndroidManifest.xml. Something like below:
</manifest>
<application
...
android:theme=""Theme.AppCompat.Light" >
...
</application>
</manifest>
I'm doing the same exercise in the Udacity and that worked for me, I hope it helps.
I assume you want the share view appears beside the toolbar menu!
If yes, here is the right solution for your issue :
DetailActivity.java
package com.example.android.sunshine.app;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
DetailFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public static class DetailFragment extends Fragment {
private static final String LOG_TAG = DetailFragment.class.getSimpleName();
private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
private String mForecastStr;
public DetailFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
// The detail Activity called via intent. Inspect the intent for forecast data.
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
mForecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
((TextView) rootView.findViewById(R.id.detail_text))
.setText(mForecastStr);
}
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.menu_detail_fragment, menu);
// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent.
ShareActionProvider mShareActionProvider =
(ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// Attach an intent to this ShareActionProvider. You can update this at any time,
// like when the user selects a new piece of data they might like to share.
if (mShareActionProvider != null ) {
mShareActionProvider.setShareIntent(createShareForecastIntent());
} else {
Log.d(LOG_TAG, "Share Action Provider is null?");
}
}
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,
mForecastStr + FORECAST_SHARE_HASHTAG);
return shareIntent;
}
}
menu_detail_fragment.xml
<?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">
<item android:id="#+id/action_share"
android:title="#string/action_share"
app:showAsAction="always"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />
</menu>
menu_detail.xml
<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="com.example.android.sunshine.app.DetailActivity" >
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
</menu>

Can't add action buttons on action bar

I want to add an ActionButton on the ActionBar, but it is placed on the overflow. What i'm doing wrong?
below is a code file and the main class
///--main_activity_actions.xml--///
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action buton -->
<item android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
android:showAsAction="ifRoom"/>
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:showAsAction="never" />
</menu>
//--MainActivity.java--//
package com.example.my_first;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater =getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch(item.getItemId()){
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openSettings() {
// TODO Auto-generated method stub
}
private void openSearch() {
// TODO Auto-generated method stub
}
public void sendMessage(View view){
//Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
If you want an action to have its own icon on the ActionBar, try changing
android:showAsAction="ifRoom"
to
android:showAsAction="always"
Add this schema to your menu resource:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
Then change the showAsAction attribute:
<item android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
app:showAsAction="ifRoom" />
Took me days to figure that out. Answer was here.

How do I create a clickable item in menu to open a new activity?

I have made an app with a lot of buttons and activities. I'm having trouble though understanding how to start a new activity through a button that is in my menu (when the menu button is clicked on phone) (inflatable menu). This is my code for the menu connected to my activity:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/item1" android:title="#string/menu_home"></item>
</menu>
Here is my activities in Java:
package com.gmail.derekcraigsmith.nanaimobus;
import android.os.Bundle;
import android.app.Activity;
import android.content.ClipData.Item;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
public class Route1TimesCcMonfriAActivity extends Activity implements
OnMenuItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.route1_times_cc_monfri_a);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.route1_times_cc_monfri_a, menu);
return true;
}
#Override
public boolean onMenuItemClick(MenuItem item) {
// TODO Auto-generated method stub
return false;
}
}
int id = item.getItemId();
switch (id) {
case R.id.your_menu_item_id : {
startActivity(new Intent(start_activity, next_activity));
}
where start activity is your main activity and next_activity is the activity you want to start.
Give a look on my blog here for more info.
activity_main.xml in menu folder
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/next"
android:title="Next" />
</menu>
In your activity inflate the menu
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) //get the id which is an int
{
case R.id.next: // check if its the menu item next selected
// Single menu item is selected do something
// Ex: launching new activity/screen or show alert message
Toast.makeText(MainActivity.this, "Next Selected", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this,secondAct.class));//start activity
break;
default:
return super.onOptionsItemSelected(item);
}
}

Categories

Resources