I'm trying to create the Action Bar by following the Android Studio tutorial. I am familiar with VBA, C++, and Python, but this is the first time I've ventured into an App, which uses java, xml, etc. in one. I say that because I think I've misplaced (or misnamed) something in my code, as when I try to run this, I get the error error: duplicate class: com.example.batman.myfirstapp.MyActivity.
I don't understand how it's a duplicate, I only have one "MyActivity.java", so am thinking that I can't do more than one public class MyActivity extends ... per .java file?
Here's what I have (please let me know if I need to include other code):
MyActivity.java
package com.example.batman.myfirstapp;
import android.content.Intent;
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;
import android.support.v7.app.*;
public class MyActivity extends ActionBarActivity{
#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);
}
#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);
}
}
}
public class MyActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = ".com.batman.myfirstapp.MESSAGE";
/**
* Called when the user clicks the Send button
*/
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);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// If your minSdkVersion is 11 or higher, instead use:
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
main_activity_actions.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myfirstapp="http://schemas.android.com/apk/res-auto">
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
myfirstapp:showAsAction="ifRoom" />
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
myfirstapp:showAsAction="never" />
</menu>
Again, I'm not sure what other files (strings.xml, DisplayMessageActivity.java, etc.) would be helpful to debug the above, so let me know what else I can include.
Thank you for any advice/help!
You're intuition is correct! You can only have one MyActivity class in your file, here's what it might look like:
public class MyActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = ".com.batman.myfirstapp.MESSAGE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private 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);
}
}
Your assumption is correct. In your .java file you have two classes named MyActivity. You can only have one.
Related
I have create a menu with couple options, but I want to get a separate page when I click on them in MainActivity. As in: if I click on Movies, I would have other page showing lists of movies and so on.
Which functions should I call for that?
package com.example.popupmenu.popupmenu;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.PopupMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity implements PopupMenu.OnMenuItemClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
public void showPopUp(View v){
PopupMenu popup=new PopupMenu(this,v);
popup.setOnMenuItemClickListener(MainActivity.this);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu. main_menu, popup.getMenu() );
popup.show();
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.Movies:
Toast.makeText(getApplicationContext(), "movies Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.MeloDramas:
Toast.makeText(getApplicationContext(), "Melodramas Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.Songs:
Toast.makeText(getApplicationContext(), "Songs Selected", Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
//return false;
}
}
On Your menu Click do this thing to StartActivity.
case R.id.Movies:
Intent launchNewIntent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(launchNewIntent);
return true;
this will open new Activity.
Create a movie list activity. Then in your menuitemclick function in MainActivity, call intent to MovieActivity.
For eg;
Intent intent = new Intent(MainActivity.this, MovieActivity.class);
startActivity(intent);
You can start a new activity by using startActivity. To learn more about starting activities please visit this link.
Intent intent = new Intent(MainActivity.this, MovieActivity.class);
startActivity(intent);
first of all you didn't called showPopUp(View v) you need to call that for inflating menu. and if you want regular menu then why you are using popup menu.. just use this for inflating 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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.Movies) {
Intent i = new Intent(MainActivity.this,SplashScreen.class);
startActivity(i);
return true;
}
if (id == R.id.MeloDramas) {
Intent i = new Intent(MainActivity.this,melodramas.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
In this case you don't need to call any method just put these two method..
i would advise you to use fragments based on MenuItem selected
public boolean onMenuItemClick(MenuItem item)
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 am using actionbar compat in my application first time. I want to add another activity to the application. When i press a SETTINGS from actionbar, i like to start the second activity.
How is possible ?
codes for my application as follows
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#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.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.action_settings:
Toast.makeText(getBaseContext(), "You selected Settings", Toast.LENGTH_SHORT).show();
startActivity( new Intent().setClass(this, SecondActivity.class));
break;
}
return true;
}
}
mainactivity image
Secondactivity.java
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
// TODO Auto-generated method stub
}
}
secondactivity image
thanks in advance
Just use a
Intent intent = new Intent(this, YourActivityToStart.class);
startActivity(intent);
on the position where you pop up a Toast.
Using 'app' instead of 'android' namespace prefix for 'actionLayout' attribute fixed it for me.
So, basically, use
app:actionLayout="#layout/yourLayout"
instead of
android:actionLayout="#layout/yourLayout"
I am assuming you are using app_compat library to get the theming engine.
I'm creating an app for Android and I wanted to make items in the context menu.
This wasn't a Problem and they were shown. But when I click on them, nothing happens.
I configured the things I needed to configure, but I really am not able to find the Problem. Do you see something? Here my complete code of the Main-Java-Code.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.loadUrl("ABC");}
#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);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.optionsmenu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem about) {
//respond to menu item selection
switch (R.menu.optionsmenu) {
case R.id.about:
startActivity(new Intent(this, SecondActivity.class));
return true;
case R.id.download:
startActivity(new Intent(this, DownloadActivity.class));
return true;
case R.id.impressum:
startActivity(new Intent(this, ImpressumActivity.class));
case R.id.license:
startActivity(new Intent(this, LicenseActivity.class));
}
return false;
}
I want them to Show the Activitys, but nothing happens.
Thanks for your help
Thanks to Phil, the item selection is now working. Here my other codes, the app breaks down every time I select the others.
Here is LicenseActivity:
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
/**
* Created by Florent on 16.08.13.
*/
public class LicenseActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView myWebView = (WebView) findViewById(R.id.licenseview);
myWebView.loadUrl("URL");
}
}
Second Activity is only a design activity, the other activitys are the sames as the License Activity.
I see your misstake. You need to get the menuitems Id inside the switch using MenuItem.getItemId(), and return return super.onOptionsItemSelected();:
public boolean onOptionsItemSelected(MenuItem about) {
//respond to menu item selection
switch (about.getItemId()) { // call this here
case R.id.about:
startActivity(new Intent(this, SecondActivity.class));
return true;
case R.id.download:
startActivity(new Intent(this, DownloadActivity.class));
return true;
case R.id.impressum:
startActivity(new Intent(this, ImpressumActivity.class));
case R.id.license:
startActivity(new Intent(this, LicenseActivity.class));
}
return super.onOptionsItemSelected(about); // return this instead of false
}
Also, do not forget to register your Activities inside your Manifest file.
And make sure you are calling setContentView(...) inside your Activity's onCreate() method.
public class LicenseActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.whateveryourlayoutis); // DONT FORGET THIS
WebView myWebView = (WebView) findViewById(R.id.licenseview);
myWebView.loadUrl("URL");
}
}
I'm using SlidingMenu implementation in my app, I want the android.R.id.home button to open/close the side menu. Inside the Activity I use Fragment to display information. I want the home button to act as a back button.
The problem is that Activity's onOptionsItemSelected in Activity get invoked before the Fragment's one. Is this ordinary behavior? Or am I doing something wrong?
I'm using ActionBarSherlock in my project as well, but I don't think that matters tho.
Is implementing my own interface the only solution here?
Exactly last night I was struggling with this but eventually managed to solve it, so here is my solution:
These are the relevant parts from MainActivity:
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
public class MainActivity extends SherlockFragmentActivity {
.
.
.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
return super.onOptionsItemSelected(item);
}
}
Here is my menu main.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/action_settings"/>
</menu>
and here is my Fragment:
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class TestFrag extends SherlockFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.
.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add(Menu.NONE, android.R.id.home, 100, "Home");
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId())
{
case android.R.id.home:
// Do whatever you want when Home is clicked.
Toast.makeText(getSherlockActivity(), "Home is clicked", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
This is what I am getting:
I hope this helps in any way.
Ended up moving the onOptionsItemSelected from Activity to my base Fragment class instead.
Inside base fragment class, I have these:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
// Toggle slide menu
getBaseActivity().getSlidingMenu().toggle(true);
break;
}
return super.onOptionsItemSelected(item);
}
protected boolean useHomeAsBack(MenuItem item){
switch(item.getItemId()){
case android.R.id.home:
Log.v(TAG, "useHomeAsBack - onOptionsItemSelected");
getSherlockActivity().onBackPressed();
return true;
}
return false;
}
Also call setHasOptionsMenu(true); inside onAttach as well.
Inside the actual Fragment that I wanted to use back instead, I have:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(useHomeAsBack(item)) return true;
return super.onOptionsItemSelected(item);
}
Still, I'd expect Fragment's onOptionsItemSelected to be able to override or take priority over Activity's. Wonder what the reason for that would be.