Can't replace AppCompatActivity with Activity - android

I'm a beginner to android programming.So could not get what the methods are in the MainActivity class. Of course googled it. But didn't find the answer. Every tutorial asking to extend the main class from Activity,but I'm not able to do it. Any answes, explanations, suggestions are appreciated.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#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.menu_main, 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) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

AppCompatActivity is the latest Activity class (Its inheritance is Activity) that provide compatilibity with old phones (from 2.1+, api 7) so it will follow the activity life cycle (onCreate, onStart, onResume, onPause, onStop, onDestroy).
With the AppCompatActivity you can use all the methods from activity and also have access to Fragments (for dynamic UI via SupportFragmentManager), Loaders (for sql queries via SupportLoaderManager), the Action bar (via SupportActionBar).
To Summarized: AppCompatActivity = Activity + Support for old phones.

AppCompatActivity is what you can use instead of Activity for v21+ of the android sdk.
As for the methods, in your example:
onCreate - infaltes the layout and you can do a lot of the instantiation in this method, read intent extras etc.
OnCreateOptionsMenu - inflates the menu for the view that you have specified in res/menu which appears on the action bar.
OnOptionsItemSelected - you can specify the actions that should be initiated when a menu item is clicked.

And if you try extends your class to ActionBarActivity?

Related

How to add actionbar menu from mainactivity to another activity?

I was wondering if someone could help me with a question I have about the actionbar? I recently had trouble with another activity in my android app but got that fix by setting apptheme.noactionbar in my manifest file but now decided. I think I would like to have an actionbar menu on my other activity like I have on my MainActivity page. I been looking up answers on adding an actionbar menu to my second activity but couldn't figure out how to do it. I try several answers but they aren't working for me. I even try switching apptheme.noactionbar to apptheme.actionbar and it still not helping. I did find some other new answer on how to add the actionbar but I not sure if I can remove the toolbar code in my OnCreate method and replace it with the code (found in this answer). So, I not sure if I'm doing it right, if I missing something I'm suppose to added to make it work or if I'm not understand it right that it will't work?
I just not sure what to do, I done advance coding before but never did an actionbar menu before on an activity. I did make another menu in the menu folder, so that the menu of this activity would be different than the menu from the MainActivity. So, I will post my here below and was wondering if anyone would please look at it and tell me what I doing wrong?
Thank you in advance for the help!
My Code
New Activity (trying to add actionbar menu to activity that app starts after MainActivity)
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
public class results extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#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_results, 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) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here the code for my new activity, if any other parts of my app source is need, please let me know. I will post it here then.
Any suggestions?
just extend activity with main activity in which you want actionbar.

How to use default back button plus adding activity to stack in Android Application

I am using Android Studio to make an application that starts with activity A and then with a button press goes to activity B that contains some other buttons that extend into their own activities.
I want to use the back button to just go back to the previous activity - which I read was the default action in the android devs documentation page... However, my app just exits when I am on activity B or one of the others that extend it when i press the back.
I think my problem is that I am not pushing my activities to the stack, so that's why it exits? Because there is nothing in the stack?
I have read on a lot of questions this same question, but I still understand.
So if I have two Java classes Activity A and Activity B and a Main.
The main will use an intent to start the activity A. And then through a button in A, activity B will open. Now i want to press back on my device and it goes back to A. And if i press back in A, it exits.
what i found which i should use?
#Override
public void onBackPressed() {
// do something on back.
return;
}
I have called activity A and B differently.
A is Timer and B is aboutme_help.
Timer:
public void openAboutme(View view) {
setContentView(R.layout.activity_aboutme_help);
}
aboutme_help:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class aboutme_help extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aboutme_help);
}
#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_aboutme_help, 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) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Perhaps a sample application some one can point me to that contains this simple functionality.
You can simply set up the manifest file so that Activity A is the Parent of Activity B. Thus it will know to go back when pressed. So in the manifest file under the acitivity sect for Activity B :
android:parentActivityName="com.package.ActivityA"
ActivityA is the name of your java class and not the XML file name and com.package is the name of your package
public void openAboutme(View view) {
setContentView(R.layout.activity_aboutme_help);
}
What this does is it replaces the content of current activity with a new layout. If you call this in activity A, you never leave activity A, so back button naturally closes the app if it's the first activity.
This is how you start an activity in Android:
Intent i = new Intent(this, ActivityB.class);
startActivity(i);
Don't forget to define your activities in the manifest.
Note 1:
Please follow Java naming conventions. In Java class names are in pascal case (FirstLetterOfWordIsCapital). AboutActivity is certainly a better name as one can see it is an activity by looking at the class name.
Note 2:
Your tutorial should have mentioned how to start another activity in the first place. Update your question with a link to your tutorial.

MainActivity.java action_settings cannot be resolved or is not a field

This is the only error I have now in my MainActivity.java.
The line "if (id == R.id.action_settings)" which is created by eclipse gives the error :"action_settings cannot be resolved or is not a field"
I appreciate your help to solve it
package chapter.two.hello_world;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
WorldGen earth = new WorldGen("Earth", 5973, 9.78);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setStartUpWorldValues();
}
protected void setStartUpWorldValues(){
earth.setPlanetColonies(1);
earth.setPlanetMilitary(1);
earth.setColonyImmigration(1000);
earth.setBaseProtection(100);
earth.turnForceFieldOn();
}
protected void setStartUpScreenText(){
TextView planetNameValue = (TextView)findViewById(R.id.dataView1);
planetNameValue.setText(earth.planetName);
TextView planetMassValue = (TextView)findViewById(R.id.dataView2);
planetMassValue.setText(String.valueOf(earth.planetMass));
TextView planetGravityValue = (TextView)findViewById(R.id.dataView3);
planetGravityValue.setText(String.valueOf(earth.planetGravity));
TextView planetColoniesValue = (TextView)findViewById(R.id.dataView4);
planetColoniesValue.setText(String.valueOf(earth.planetColonies));
TextView planetPopulationValue = (TextView)findViewById(R.id.dataView5);
planetPopulationValue.setText(String.valueOf(earth.planetPopulation));
TextView planetMilitaryValue = (TextView)findViewById(R.id.dataView6);
planetMilitaryValue.setText(String.valueOf(earth.planetMilitary));
TextView planetBaseValue = (TextView)findViewById(R.id.dataView7);
planetBaseValue.setText(String.valueOf(earth.planetBases));
TextView planetForceFieldValue = (TextView)findViewById(R.id.dataView8);
planetForceFieldValue.setText(String.valueOf(earth.planetProtection));
}
#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) {
// 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();
if (id == R.id.action_settings) { // the error is here
return true;
}
return super.onOptionsItemSelected(item);
}
}
Most likely your R.menu.main xml file does not contain an item having #+id/action_settings as its id. Check your R.menu.main xml file ans make sure the action_settings id is set.
As say Quanturium this mean you don't have an item with this name. But as you are talking about "action_setting" you're in fact talking about special item which are not commonly in the XML main file.
Note: I'm not a "pro" in Android, so I just hope this will help.
Have a look at the folder on the left of Android Studio. You have one named "res". Inside you have drawable, values etc... Do you have one named "menu"?
If not create one: clic right on "res", select "New / Android ressource directory" and give "menu" as name.
Now we have a folder which will contain the data for our menu, like action_settings etc...
Now, clic right on this new folder and select "New / Menu ressource file".
The name you'll give must be the name of the activity.
Eg you have a Java piece of code named "Creation", the activity (in the layout folder) is named "activity_creation.xml", so in the menu folder you have to give "creation" as name of the file, which will be created as "creation.xml".
Now, in this file you have to write:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="net.XXX.YYY.ZZZZ" >
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
android:showAsAction="never" />
where XXXX and YYYY are the directory of your app (same as yu write in top of yur Java code), and ZZZZ is the name of the activity (so in my example "creation")
As know you have a "menu", and an action_settings, in your code the following lines will be OK:
#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) {
// 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Understanding the goal of each folder in Android is a bit hard but necessary as a lot of "smalls problems" came from that.

Can't find the findViewById function

I'm an Android newbie working with the Eclipse IDE and the Android SDK. Anyway, I've watched a few tutorials and I can't seem to be able to call the findViewById() function.
I would appreciate if you could instruct me how to use it, if it's a method of a static class or something else.
Thanks, I'm sure this won't be a problem for the more advanced users!
Well the in response to the comments I'm trying to use it in an Activity.
Here's the code in there:
package tk.quiero.test1;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
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) {
// 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Where exactly am I supposed to use it?
Thanks
findViewById is defined in the Activity class, so it sounds like you're trying to call this from outside of the Activity. If so, you should post what exactly you're trying to do because there are ways of doing this, but there's also a high likelihood that there's a cleaner or easier way than resolving UI elements outside of the Activity
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.xxxxx)
}
replace xxxxx with the id that you've defined in your xml...which should look like #+id/xxxxx

How do I make a slide left/right menu in Android?

I'm trying to create a small game on Android and have some questions on a specific section of my game. I'm fairly new to android so please excuse if I don't have a full understanding of certain things.
When clicking "play" I'd like to view slide-able menu that makes it able for the user to swipe left and right to choose a level. Overtime I will be adding few more levels but have 2-3 of them now.
What would be the best way to do this? Is it best to implement a fragment for each "level page" or create entirely new activities?
My project is compatible for Android ver. 2.3.3 and above, so it's automatically included the "appcompat_v7" project. (I don't know if that makes a difference).
I've pasted my code below if needed:
package com.example.snake;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class SnakeLevelSelectActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snake_level_select);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).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.snake_level_select, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_snake_level_select, container, false);
return rootView;
}
}
}
What I intended to do was create several fragment classes and animate between the fragments when the user swipes. I also have issues understanding on how to use several fragments with the "PlaceHolderFragment" class, since the solutions I've found on SO have been different. This is an entirely question, but would be appreciated if it was answered as well.
What would be the best way to do this? Is it best to implement a fragment for each "level page" or create entirely new activities?
This is exactly what a Fragment is for. What you are looking for is already there and named ViewPager. Using ADT and Eclipse you can even create an Activity with this already implemented. Use the "Navigation type" combobox for that purpose:
You can also choose "Action Bar Tabs (with ViewPager)", which will enable Tabs in the ActionBar and make sure that you can switch to different Fragments using both the swipe gesture as well as the tabs.
Android now has this built-in in the SDK.
They call it the Navigation Drawer.
Look up the documentation it contains sample project, it is very easy to implement.

Categories

Resources