Can a new Android activity be created using an existing layout? - android

It seems that a new layout must be created when a new Android activity is created with the wizard in Eclipse. Whenever I create a new Android activity using an existing layout, I have to create a dummy layout, change the layout in onCreate() with setContentView(), then delete the dummy layout.
What is the best way to do this?

Edited Post: If you click File > New > Other, you can choose "Android > Android Activity".
Click next, and fill in the right data. If you reach the "Preview" part, you can select the changes that must be performed. I called the new activity "SecondActivity", which means the layout would file would be called "second_activity.xml". If you uncheck this file in the list, it won't create this file. Then just change your setContentView to the file you want.

You are relying too much on eclipse wizards. Be a programmer. Right click on package add new "class" Give it a name. Extend Activity. Override onCreate methods. In set content view use the layout already created.
Edit: Here are exact instructions
Right click on you package. Click New. Select Class.
Give your class a name, click Ok.
package com.example.fakeapp;
public class FakeActivity {
}
Now extend Activity add in onCreate and onCreateOptionsMenu Use the layout that you need in set content view.
package com.example.fakeapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class FakeActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_activity); //use whatever layout you want.
}
#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;
}
}
Add to the manifest between the tags dont forget to create your title in your res/strings.
<activity
android:name="com.example.fakeapp.Fakeactivity"
android:label="#string/title_activity_fakeactivity" >
</activity>
I did not mean to sound arrogant. What i meant to say was learn what the wizard is doing so you can recreate it and not rely on it to do everything for you. If you are afraid of editing the manifest then that is something that you need to learn.

Related

Issue with using an xml for a second activity (R.id issue)

Hey guys so I'm a bit new to Android programming and I have an issue and need help.
So I'll use the first app that the official android site uses for training (http://developer.android.com/training/basics/firstapp/starting-activity.html)
and I'm confused about the creating second activity part. So after they've passed the intent they create a new TextView using java code (instead of XML) so I tried creating that TextView using the xml. I created a new TextView in the xml for the second activity and I give it an id like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".DisplayMessageActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:id="#+id/new_Text"/>
</LinearLayout>
and here's the java code for the second activity:
package com.example.myfirstapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.MenuItem;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = (TextView) findViewById(R.id.new_Text);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
// Show the Up button in the action bar.
// getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
All the code worked fine before I changed it. I changed
TextView textView = new TextView(this);
to:
TextView textView = (TextView) findViewById(R.id.new_Text);
but for some reason it can't find new_Text and Eclipse only suggests id's from my main.xml. Why is it that way? Is it because R.id.blabla only gets id's from main.xml? So am I forced to make layouts using java code if they're not going to be from main.xml?
Alot of confusion in this post, but for starters:
Each Activity that you intend to eventually be visable to the user gets its own XML layout. If you start a new Android project it will give u by default 1 XML layout located in the res>layout folder and 1 activity which will serve as your user facing visual activity by default.
For your purposes , some easy ways to figure out if a activity is meant to be a "visual" activity include:
*it extends activity or some other android superclass
*it has a "onCreate method (useually located towards the top of the class)
*inside that onCreate method there is a line of code called setContentView that looks something like this.
setContentView(R.layout.httpex);
The setContentView method is important bc its kind of like the glue between your activity and your xml layout. After R.layout.___ goes the name of the XML layout you would like to use.
Only after youve set your content view to the approprate view can you link the elements or "views" from ur xml layout to your activity using the id you created. like this
TextView textView = (TextView) findViewById(R.id.new_Text);
if you set the content view to httpex.xml , you can only link to views inside httpex.xml and ect...
I have a spft spot for newbs bc ik what dicks this crowd can be to new blood for their ignorance , they forget how hard it was starting out and begin to feel all this stuff is common sense and obvious, but if i were you i would head over to thenewboston[dot]com and watch the entire series before posting to many questions like this around here so you dont get flamed on.
You can only call the widgets after you have set up the view to a particular XML for your activity. For example if you have an activity call Main you will use one XML as the UI for that particular activity, so you can call widgets created in that particular XML. As you did not post your code I can only guess that you are trying to generate a second XML with the TextView and then just calling it.
At the beginning of the Activity when you set up the layout that's the XML from where you can call the widgets from, unless you inflate the view to call a second XML that is not your case I suppose.
I hope I understood your question correctly.
Add setContentView() method before findViewById() method.

In android eclipse, how can i run a second class to execute some commands?

For instance, the mainActivity.java file is really clustered and to keep it clean i created a second .java(class) where i will execute some code upon a button press. I cannot figure out how to do it at all. And i am not sure what search terms to use either so i apologize if this has been covered.
Heres what i have in my "test" application.
I have a main activity with a single button on it.
package com.test.secondclass;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button startButton;
final Intent second = new Intent(getApplicationContext(), testClass.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = (Button)findViewById(R.id.button1);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(second);
}
});
}
#Override
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;
}
}
Now here is the "second" class that i made, now remember this is very short i am just using this for an exercise program before implementing it into my actual program.
package com.test.secondclass;
import android.app.Activity;
import android.widget.Toast;
public class testClass extends Activity{
public void onCreate(){
Toast.makeText(getApplicationContext(), "Second class thinger started", Toast.LENGTH_LONG).show();
}
}
And if i try this i get a force close immediately. If i comment out the "intent" part at the very beginning of my main activity then the program runs. But it doesnt do what i want. obviously. Thanks everyone
Add an OnClickListener to send whatever information to testClass, as shown below (untested):
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent secondIntent = new Intent();
secondIntent.setClassName(myPackageName, "testClass");
startActivityForResult(secondIntent, REQUEST_CODE);
});
References here and here.
Here's my viewpoint: you are receiving a forced close due the fact that you is trying to open user interface methods (such the Toast) with no context.
IMPORTANT: I'm assuming that you already defined both classes in the manifest.xml file!
Before explaining, I'll make a brief:
Toast: this class opens a quick message, receiving as main arguments the context, the message and the time-to-show;
The context: it is the "environment" where to show. Something like a visual scope, that defines the resources you have. In most cases, you can setup it with setContentView method.
Issue Explanation, in my opinion: The "crash" occurs because you opens the Toast message with no context. An activity is a UI control very similar to a viewpage. If you call a new activity, its very like to call a new page, and so, a new context. In the seccond activity, I haven't see any context. I think that you was assuming that the context is preserved from the first activity, but it ins't because its a new activity.
How to fix:
In the seccond class, define a layout view with setContentView, or...
Reimplement your seccond class as a Service, and call it through startService, or...
Define an AIDL mechams (similar to previous fix, but more sophisticated and complex, as it enables async method calls).
Hope it has helped in some way.
Thank you ALL for the answers!! I was actually able to do what i wanted by using the "stopSelf()" command after i displayed the Toast message. I implemented a service class and when i press the button the testClass.java class gets called and runs the "toast" message then immediately exits by the "stopSelf()" command. I made sure of this by including an "onDestroy()" method which also displayed a simple toast message confirming that the service was stopping :). I usually do stuff like this using threads but it was making the main activity really messy no matter how much formatting i did. So i wanted to have a seperate class i could use.
And to the commenter EfEs, i come from programming in C# language for windows. Android is a new playground for me and im still learning. i think im doing quite well but wasnt sure how to do what i asked. But i figured it out then. And thanks for clearing up that an Activity in android is like a "WindowsForm" in C# where it is completely new GUI for the user. I didnt know that. But thanks to all for helping me with your posts!

Double ActionBar appears?

this is my first app for android, I've been an iPhone dev for 3 years, it's been a change of mindset, and I still find some things odd. First I don't know if this iPhone background might be causing some troubles, but here's what I'm trying to do:
I want to implement an ActionBar with two options working like a TabBar from iOS:
What I want is that when the user selects an action, some Activity will be presented to the user.
Here's what I'm doing so far (which isn't that much):
I'm Using ActionBarSherlock, I have 3 activities: myApp, First and Second
myapp.java only creates the ActionBar elements and loads the activity_first:
package com.example.myApp;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.view.MenuItem;
import android.os.Bundle;
import com.actionbarsherlock.ActionBarSherlock.OnCreateOptionsMenuListener;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
public class myApp extends SherlockActivity implements OnCreateOptionsMenuListener {
ActionBarSherlock mSherlock = ActionBarSherlock.wrap(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("myApp");
mSherlock.setContentView(R.layout.activity_first);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("First")
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
menu.add("Second")
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
}
The activities have nothing so far, apart from the generated stub:
import android.app.Activity;
import android.os.Bundle;
public class First extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
}
So I have 1 Question and 1 problem:
Question: Is this the correct use of an ActivityBar? I mean, should it be used to switch activities?
Problem: As you can see in the OnCreate method of myApp class, I'm loading the activity_first, It does load the activity, however it loads the ActionBar Twice, like so:
I don't get why is it being loaded twice. If I remove the line: mSherlock.setContentView(R.layout.activity_first); it loads the Bar once, obviously I need to load the activity...
Also I've assigned the NoActionBar theme to the activity_first in the graphical editor of the XML (activity_first.xml), but it doesn't work. What Can I do to load it just once.
Thank you for your valuable time.
Is this the correct use of an ActivityBar? I mean, should it be used to switch activities?
You can think of "First" and "Second" as being the equivalent of toolbar buttons in a desktop app. You are welcome to have those action bar items start up activities if you wish.
As you can see in the OnCreate method of myApp class, I'm loading the activity_first, It does load the activity, however it loads the ActionBar Twice, like so:
Delete this line:
ActionBarSherlock mSherlock = ActionBarSherlock.wrap(this);
and change mSherlock.setContentView(R.layout.activity_first); to just setContentView(R.layout.activity_first);. I believe that will clear up your problems.

Android - Creating a new activity in Eclipse [duplicate]

This question already has answers here:
Best way to add Activity to an Android project in Eclipse?
(8 answers)
Closed 9 years ago.
Easy one.
I've gone through a few guides and tutorials, and they're quite clear on how to start an activity (with intent).
However, how do I create a new activity in Eclipse? I can probably do this by hand, but then I have to modify the R file, which is auto-generated, and add a new xml layout.
Ok. Being a newbie myself I think the above two answers are thinking too much. He's asking very simply how to create a new activity in Eclipse.. I think this is what he wants:
A new Activity in Eclipse is actually a Class.
You would doubleclick 'src' on the left side in the Package Explorer, then highlight your 'com.' name, right click, select 'New' and then select 'Class'. Enter the Name as NewActivity and set the Superclass to android.app.Activity, then hit Finish.
When the NewActivity.java file opens up it should look like this:
package com.example.yourappname;
import android.app.Activity;
public class NewActivity extends Activity {
}
You can leave the Superclass blank and add extends Activity to the code itself if you prefer.
The final step is adding the Activity to your Manifest. So doubleclick AndroidManifest.xml to open it up and then click the 'Application' tab on the bottom. Next to the 'Application Nodes' box, click 'Add'. Highlight 'Activity' (the square box with a capital A) and click 'Ok'. Now look for the 'Attributes for Activity' box and enter a Name for the Activity and precede it by a period. In this example you'd enter '.NewActivity'.
And then you can add your onCreate() code so it looks like this:
public class NewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
//rest of the code
}
}
main_view would be your main view xml file, main_view.xml, that you would create in your layout directory.
To call the new Activity, your Intent in the code (in a different Activity) to start a new Activity looks something like this:
Intent startNewActivityOpen = new Intent(PresentActivity.this, NewActivity.class);
startActivityForResult(startNewActivityOpen, 0);
And that's it, you have the code to call the new activity and you created it. I hope this helps someone.
I know this is an old question, but I know there are still people with this same question(I did up until today)
If you add a new activity to your manifest file, there's a special link to click on to automatically create the new Activity, complete with the onCreate() method ready to be filled in.
Open the AndroidManifest.xml, and go to the 'Application' tab. Under 'Application Nodes', find and click the 'Add' button. You will likely create a new element at the top level, so select that option, highlight 'Activity', and press OK.
Once you've created the Activity, go to the 'Attributes for Activity' and fill in the name. Once you've filled in the name you want, click on the blue 'Name*' link next to the field. The new file wizard will show up, and all you have to do is press OK.
Voila! New Activity, registered in the manifest and as a ready-to-go Java class.
You create the activity by extending the activity class . Once you have creatd the activity class , You need to add the activity in the androidmanifest file specifying the properties for the activity...
A sample one would be something like this ...
<activity android:name=".JsonActivity" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
The action here indicates that it is the one that starts first ..
I dont think you need to modify the R.java file ... Once you add these in the android manifest file and save it automatically gets updated. Also the things that u added like the layouts, menus, strings, id's etcc.... in the various xml files also get automatically updated...
Correct me if i am wrong ...
I tried searching for this question on Google and haven't seen this solution yet, so I thought I'd post it here.
In Eclipse, you can click on the "New" button on the toolbar. Under Android, select Android Activity, and run through the wizard. This is the best solution by far, since it lets you set up a layout and an Activity all in one, while also updating the Manifest for you.
How to add New Activity Eclipse step by Step:
Stpe1:Double click on the androidManifest
Step2:on the Menu bar click Aplication
Step3:Scroll down to application node and CLick add button
Step 4:click select Activity and Ok
step 5:clik on the the Texte(Name* Note:make sur u clik on the texte
not into the textbox )
step6:there a new Java Class dialog
## Heading ##write the classe name
## Heading ## check checkbox construct from the super classe and and ok..
There is also the tried and tested method of starting with one of the samples and going from there.
The Hello tutorial is as good a starting point is any, just select the create from existing sample option.
The latest update to the eclipse plugin even includes a tool to rename your package should you change your mind though I haven't used it yet so can't say if it works. (Right click on the package then select Android Tools, Rename Application Package).
It is important to say that if you type the desired name for the new Activity on Name box, a dot must be put before the new name. Otherwise, the window to complete the creation of Java code will not open when you click on names link.

How to add a menu to MapActivity?

I've got an app using MapActivity.onCreate() to initialize the map and show it on screen. Now I would like to add a menu to my app. From what I've found out I can't add a menu from MapActivity and need to use Activity (correct me if I'm wrong).
Now I have no idea how to "initialize" the map from my Activity-class.
And how would I have to fix the views, will I wrap my activity-layout around my Map-layout?
MapActivity extends a regular Android Activity, so there's nothing irregular you should need to do to create a menu.
Just override the onCreateOptionsMenu method, as shown in the developers' guide.
MapActivity extends Activity, so you should be able to add a menu.
MapActivity is a subclass of Activity, and thus you do it the same way as in any normal Activity (instructions here). I've been able to successfully create menus the same way in MapActivity as in a normal Activity.
Make sure that it doesn't extend from FragmentActivity but from AppCompatActivity!
If that's the case, the onCreateOptionsMenu method will be called and you are able to overwrite it like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu); //"menu_main" is the XML-File in res
return super.onCreateOptionsMenu(menu);
}

Categories

Resources