This is the program i am doing I have created two items in main.xml i.e "About Us" And "Preferences" which i want to use in my program but when i am trying to access the main.xml using inflate method in MenuInflater it cannot find my resource.
package com.sagar.firstapp;
import android.R;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Menu extends ListActivity{
String classes[]={"StartingPoint","TextPlay","Email","Camera","Data","example5"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter(Menu.this,android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String cheese=classes[position];
try {
Class ourclass=Class.forName("com.sagar.firstapp."+cheese);
Intent ourintent=new Intent(Menu.this,ourclass);
startActivity(ourintent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater blowup=getMenuInflater();
blowup.inflate(R.menu.main, menu);/*Can't find my main.xml resource*/
return true;
}
}
here is my main.xml code
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:title="About Us"
android:id="#+id/aboutus"
android:numericShortcut="1"
android:alphabeticShortcut="a"/>
<item
android:title="Preferences"
android:id="#+id/preferences"
/>
R.java(Generated lines)
public static final int aboutus=0x7f09001d;
public static final int preferences=0x7f09001e;
public static final class menu {
public static final int main=0x7f080000;
}
Create a main.xml under res/menu folder
main.xml
<menu xmlns:androclass="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/item1"
android:title="About Us"/>
<item android:id="#+id/item2"
android:title="Preferences"/>
</menu>
and in your Activity call inflate() in onCreateOptionsMenu(menu menu)
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);//Menu Resource, Menu
return true;
}
Related
I'm implementing an action bar for my app which has 2 menu buttons : Add and Settings. In Designer view the 2 buttons still apprear like normal. However when I run the app 2 buttons does not show up at all. Please help
Below are my code:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
MainActivity.Java
package com.example.sunny.mynote;
import android.app.ActionBar;
import android.app.ListActivity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.sunny.mynote.com.example.sunny.mynote.data.NoteDataSource;
import com.example.sunny.mynote.com.example.sunny.mynote.data.NoteItem;
import java.util.List;
public class MainActivity extends ListActivity {
public static final int EDITOR_ACRIVITY_REQUEST = 1001;
public static final int SETTINGS_REQUEST = 1003;
private static final int MENU_DELETE_ID = 1002;
private int currentNoteId;
private NoteDataSource datasource;
List<NoteItem> notesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerForContextMenu(getListView());
datasource = new NoteDataSource(this);
refreshDisplay();
}
private void refreshDisplay() {
notesList = datasource.findAll();
ArrayAdapter<NoteItem> adapter =
new ArrayAdapter<NoteItem>(this, R.layout.list_item_layout, notesList);
setListAdapter(adapter);
}
//Add the Actions to the Action Bar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
//Respond to Action Buttons
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_create:
createNote();
return true;
case R.id.action_settings:
Settings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void createNote()
{
NoteItem note = NoteItem.getNew();
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra("key", note.getKey());
intent.putExtra("text", note.getText());
startActivityForResult(intent, EDITOR_ACRIVITY_REQUEST);
}
private void Settings()
{
Intent intent2 = new Intent(this, Settings.class);
startActivityForResult(intent2, SETTINGS_REQUEST);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
NoteItem note = notesList.get(position);
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra("key", note.getKey());
intent.putExtra("text", note.getText());
startActivityForResult(intent, EDITOR_ACRIVITY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EDITOR_ACRIVITY_REQUEST && resultCode == RESULT_OK)
{
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
NoteItem note = new NoteItem();
note.setKey(data.getStringExtra("key"));
note.setText(data.getStringExtra("text"));
datasource.update(note);
refreshDisplay();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
currentNoteId = (int)info.id;
menu.add(0, MENU_DELETE_ID, 0, "Delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId() == MENU_DELETE_ID)
{
NoteItem note = notesList.get(currentNoteId);
datasource.remove(note);
refreshDisplay();
}
return super.onContextItemSelected(item);
}
}
menu.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=".MainActivity">
<item android:id="#+id/action_create" android:title="#string/action_create"
android:icon="#drawable/create_note"
android:orderInCategory="100" app:showAsAction="ifRoom" />
<item android:id="#+id/action_settings" android:title="#string/action_settings"
android:orderInCategory="100" app:showAsAction="ifRoom" android:icon="#drawable/ic_settings"/>
</menu>
Use in Your Java File after setContentView
getSupportActionBar().show();
I would like to see you menu xml file for this Activity.
Please try this one, change icon and id.
Notice that there is android:showAsAction="always" NOT app:showAsAction="always":
<item android:id="#+id/Add_New_Note"
android:icon="#drawable/ic_action_new"
android:title="Add new note"
android:showAsAction="always"/>
I had the same problem, hope it will help.
Include this code in your MainActivity
public class MainActivity extends ActionBarActivity {
Inside your onCreate()
ActionBar actionBar = getSupportActionBar();
Give Add and Settings Item in res -> Menu folder.
It will display ActionBar.
Give your extends ListViewActivity in findViewById
add in menu.xml app:showAsAction="ifRoom" like this:
<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=".Main">
<item android:id="#+id/paste" android:title="Paste"
android:orderInCategory="100"
app:showAsAction="ifRoom" />
</menu>
and in main:
//Add the Actions to the Action Bar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
//Respond to Action Buttons
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
see this: https://developer.android.com/training/basics/actionbar/adding-buttons.html
I'm trying to display the Search Icon in the top right of my Actionbar.
See Code below for the PublicVideos.java that extends an ActionBarActivity
The getoverflow manages to display the overflow menu, but it does not display the search icon. I have added the different sizes search icons in their respective drawables folders.
package faith.faithconnect;
import java.lang.reflect.Field;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
public class PublicVideosActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_public_videos);
centreLogo();
getOverflowMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.faithmenu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
return super.onCreateOptionsMenu(menu);
}
private void getOverflowMenu() {
// TODO Auto-generated method stub
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class
.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void centreLogo() {
// TODO Auto-generated method stub
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#F7CE04")));
// getOverflowMenu();
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setCustomView(R.layout.public_videos_view);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_action_back);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent backhome = new Intent(this, MainActivity.class);
startActivity(backhome);
}
// public void mingleSwipe(View view)
// {
// Intent mingleintent = new Intent(getApplicationContext(),
// MingleActivity.class );
// startActivity(mingleintent);
//
// }
public void ratingSelected(View view) {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Try Google play
intent.setData(Uri
.parse("market://details?id=com.cubeactive.qnotelistfree"));
startActivity(intent);
}
public void shareSelected(View view) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "subject here");
shareIntent.putExtra(Intent.EXTRA_TEXT, "body here");
startActivity(Intent.createChooser(shareIntent, "Share Via"));
}
}
The faithmenu.xml 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/action_search"
android:title="search"
android:icon="#drawable/ic_action_search"
android:showAsAction="ifRoom|collapseActionView"
android:actionViewClass="android.support.v7.widget.SearchView" ></item>
</menu>
You should use name space app for showAsAction, so it should be:
<?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_search"
android:title="search"
android:icon="#drawable/ic_action_search"
app:showAsAction="ifRoom|collapseActionView"
android:actionViewClass="android.support.v7.widget.SearchView" > </item>
</menu>
When your item have android:showAsAction="ifRoom" If there's not enough room for the item in the action bar, it will appear in the action overflow.
You can also use "always" (android:showAsAction="always") to declare that an item always appear as an action button. However, you should not force an item to appear in the action bar this way. Doing so can create layout problems on devices with a narrow screen. It's best to instead use "ifRoom" to request that an item appear in the action bar, but allow the system to move it into the overflow when there's not enough room.
I am trying to create a spinner, the values of which I am populating from a resource xml, using ArrayAdapter.
I also want to give the resource items some "id" or "value". How can i retrieve these values inside the onItemSelected() callback ?
Here is the Java code.
package com.waus.waus;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class Register extends Activity implements OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
Spinner countrySpinner = (Spinner) findViewById(R.id.country_code_spinner);
ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(this, R.array.country_codes, android.R.layout.simple_spinner_item);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
countrySpinner.setOnItemSelectedListener(this);
countrySpinner.setAdapter(countryAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(this, "THIS IS WHERE I WANT TO SHOW THE ID/VALUE" ,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
This is the XML file I want to use.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="country_codes">
<item value="91">India</item>
<item value="1">United States</item>
// OR
<item id="1">United States</item>
</string-array>
</resources>
How can it be done without using 2 resource files. i.e. one for codes and another for names.
String[] SortByField= activity.getResources().getStringArray(
R.array.country_codes);
or
Arrayadapter adapterFillClass = ArrayAdapter.createFromResource(activity,
R.array.country_codes,
android.R.layout.simple_spinner_dropdown_item);
spinner.setadapter(adapterFillClass);
i hope it useful to you.
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);
}
}
I am trying to use the menu inflator to give the user the option to email me for support, but everytime I hit the menu button on the emulator it will do nothing.
Would I need to edit this in my manifest? My xml has menu as the title and items for the well items.
Here is my xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/email" android:title="#string/email_menu"
android:icon="#drawable/ic_envelope" android:onClick="emailme" />
<item android:id="#+id/test1" android:title="#string/test1"
android:icon="#drawable/ic_dashboard" android:onClick="test1" />
</menu>
Activity:
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MenuButton extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.menu.menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.email:
emailme();
return true;
case R.id.test1:
test1();
return false;
default:
return super.onOptionsItemSelected(item);
}
}
private void test1() {
// TODO Auto-generated method stub
}
private void emailme() {
// TODO Auto-generated method stub
String domsEmail = "MYEMAIL#EXAMPLE.com";
String message = "Hello, I just want to let you know that your app";
String myemail[] = { domsEmail };
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, myemail);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "your app");
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
startActivity(emailIntent);
}
}
Here are various issues with your code:
Please have onCreateOptionsMenu() use return(super.onCreateOptionsMenu(...)) with the same parameters that you receive -- in other words, chain to the superclass when you are done
Your android:onClick attributes will only work on API Level 11 and higher, and your methods that you have tied to them need to be public and have a MenuItem parameter (which yours do not)
Your MIME type in emailme() needs to be text/plain, not plain/text