I'm trying to work through the "Start Another Activity" tutorial but, having worked through the whole thing (twice), the app still refuses to return the text entered in the textbox - it always returns "Hello World".
I've tried to figure it out, and suspect it might be something to do with the fragment_display_message.xml, in which there is an EditText calling the Hello World string. But really I have no idea.
Any help would be appreciated. Here's the code:
MainActivity.java
package com.knargle.streetiteatit;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.knargle.streetiteatit.MESSAGE";
/** Called when the user clicks the Send button */
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);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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.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);
}
/**
* 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_main, container,
false);
return rootView;
}
}
}
fragment_main.xml
<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"
android:orientation="horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.knargle.streetiteatit.MainActivity$PlaceholderFragment" >
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
DisplayMessageActivity.java
package com.knargle.streetiteatit;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#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 = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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_display_message,
container, false);
return rootView;
}
}
}
fragment_display_message.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.knargle.streetiteatit.DisplayMessageActivity$PlaceholderFragment" >
<EditText android:id="#+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/hello_world" />
</RelativeLayout>
In your DisplayMessageActivity.java file, you are calling setContentView twice which it-self is overwriting the first line of code. Currently your code looks like this:
setContentView(textView);
setContentView(R.layout.activity_display_message); // Delete this line. As this line of code appears in your java file, it is overwriting the 'text' you entered with the default 'hello world' message
It should be just like this:
setContentView(textView);
The setContentView is being called twice in DisplayMessageActivity. Remove the second one:
setContentView(R.layout.activity_display_message);
In your DisplayMessageActivity:
// Set the text view as the activity layout
setContentView(textView);
setContentView(R.layout.activity_display_message);
You call setContentView twice, which just overwrites what was already there. Remove the second setContentView.
You can follow the answers from both Andrew and Rajesh. But the fact that you have defined a layout fragment_display_message and I am sure you want to use it. In that case, all you need to do is get rid of the code to dynamically add the TextView and the correspodning setContentView and leave the second setContentView that uses your layout. Once done, you get the reference to your EditText and set it's text to what was sent in the Intent.
Remove these lines from DisplayMessageActivity :
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
You were attempting to set the message in a new text view which is not part of your layout file. And then setting that text View as the ContentView of your layout. That seems like a convoluted approach. Instead try the following :
After the setContentView(R.layout.activity_display_message); line, add these lines :
EditText editText = (EditText) findViewById(R.id.edit_message);
editText.setText(message);
This way, you use the existing Edit text element in your layout file to show the message. Your original code never replaced HelloWorld in this element. That is why it always shows you HelloWorld instead of your message.
Related
Please look at the following algorithm and tell me if I can achieve it:
create a main_activity
inside the main_activity, create a simple Button
the Button is labeled as "Add Button"
once the users clicks the Button, an additional Button is created and placed in the Activity.
In other words:
once the user clicks on the add Button, it should create another Button and
place it under the "Add Button" Button.
I apologize in advance as this may be confusing, so please feel free to comment and ask for clarification.
I originally thought about creating a separate method, in which I would create a ButtonView, but I am not sure how I can physically create a Button.
Would I need to apply code to .xml file also?
I am really confused.
Here is my code:
MainActivity.java
package inc.fimp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addArm = (Button) findViewById(R.id.btnAddArm);
addArm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addButton();
}
});
}
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
int res_id = item.getItemId();
if(res_id==R.id.action_contact)
{
Toast.makeText(getApplicationContext(), "You selected Contacted us option", Toast.LENGTH_SHORT).show();
}
if(res_id==R.id.action_settings){
Toast.makeText(getApplicationContext(), "You selected Settings Option", Toast.LENGTH_SHORT).show();
}
return true;
}
public void addButton(){
// create an aditional button
}
}
xml file code
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="inc.fimp.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_arm"
android:textStyle="italic"
android:id="#+id/btnAddArm"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/addarm"
android:singleLine="false" />
</RelativeLayout>
Start by adding an ID to the parent layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/buttonContainer"
Then, get that with findViewById. ViewGroup simply used because that is all you need to get the addView method.
public class MainActivity extends AppCompatActivity {
private ViewGroup rootView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rootView = (ViewGroup) findViewById(R.id.buttonContainer);
Then, in the addButton,
Button button = new Button(MainActivity.this); // Need to provide the context, the Activity
// button.setText("Added!"); // for example
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.BELOW, R.id.btnAddArm);
// params.addRule ... (there's a bunch you can add)
rootView.addView(button, params);
Since you have a RelativeLayout, you can also programmatically put LayoutParams to do layout above/below, etc. other views.
I'm trying to make an app - it has 3 activities. The first 2 are listviews in linear layouts, and each of them prevents the title bar from showing up. By title bar I mean the section that is normally at the top of an activity which displays the activity's name as well as an option setting. My third activity is not a listview, and displays the title bar normally, which leads me to think it may be a problem with my listviews.
The xml for my first page is:
<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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".SelectClass">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
My java class doesn't do much to the display, although it does set an array adapter and an onClick listener. If those are necessary to understand what's going on then let me know and I'll post them. I appreciate any help or clues. Thank you!
EDIT: first page's java:
package com.example.graeme.dnd5echaracterroller;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.view.View;
import android.widget.TextView;
public class SelectClass extends ListActivity {
private static String classString;
public static void setClassString(String classString) {
SelectClass.classString = classString;
}
public static String getClassString() {
return classString;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_class);
//Initialize the available class choices
final String[] classes = {"Barbarian","Bard","Cleric","Druid",
"Fighter","Monk","Paladin","Ranger","Rogue","Sorcerer",
"Warlock", "Wizard"};
ArrayAdapter<String> classAdapter = new ArrayAdapter<>(getListView().getContext(),
R.layout.classlayout, R.id.classname, classes);
getListView().setAdapter(classAdapter);
//Set on click listener to get selected class item
AdapterView.OnItemClickListener itemClickedHandler = new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
//Start a new intent headed to selectRoll, fill it with the class string selected
Intent sendClassIntent = new Intent(SelectClass.this, SelectRoll.class);
//Each list item has an image, and text
//First grab the list item, then grab the text from it
LinearLayout ll = (LinearLayout)v;
TextView tv = (TextView)(ll).findViewById(R.id.classname);
setClassString((String)(tv.getText()));
startActivity(sendClassIntent);
}
};
getListView().setOnItemClickListener(itemClickedHandler);
}
#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_select_class, 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);
}
}
You should modify you first activity as this structure
public class SelectClass extends AppCompatActivity {
...
private ListView mListView;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_class);
// Initialize the lisview
mListView = (ListView) findViewById(R.id.lisview_id); // lisview id
//Initialize the available class choices
final String[] classes = {"Barbarian","Bard","Cleric","Druid",
"Fighter","Monk","Paladin","Ranger","Rogue","Sorcerer",
"Warlock", "Wizard"};
ArrayAdapter<String> classAdapter = new ArrayAdapter<> (this,
R.layout.classlayout, R.id.classname, classes); // update
mListView.setAdapter(classAdapter);
...
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
....
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
.....
}
}
And in the ListView of first activity
<ListView
android:id="#+id/lisview_id" // use this id for initialize listview
android:layout_width="match_parent"
android:layout_height="match_parent">
Hope this help
I think that the problem is not the ListView, normally it is hided because of the style you have set in your manifest. This is what you have in the main activity inside manifest.xml:
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
the android:theme="#style/AppTheme" on the listView activity must be set as the Apptheme that shows the "Title bar".
Hope this helps
As suggested in other threads, I am following a tutorial in order to learn the basics of android application development. However, the code for the DisplayMessageActivity class as given here contains several errors:
container can not be resolved or is not a field (line 16)
Fragment cannot be resolved into a type (line 37)
View cannot be resolved into a type (line 62)
fragment_display_message cannot be resolved or is not a type (line 62).
Wile trying to fix this error by my own a new error popped up out of nowhere at line 55: Class requires API level 11 (current min is 8);android.app.Fragment
According to another SO entry this is due to an ADT version mismatch. But this entry does not explain how to fix it.
How can this tutorial code be fixed so it compiles - or is there a 'working' tutorial available somewhere with actual working examples?
Here is the code so far:
package com.example.testapp;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_display_message);
//
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.container, new PlaceholderFragment())
// .commit();
// }
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
#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_display_message,
container, false);
return rootView;
}
}
}
Here is the content of the file res/layout/activity_main.xml:
<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"
android:orientation="horizontal" >
<EditText android:id="#+id/edit_message"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
and here the content of the file res/layout/activity_display_message.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.testapp.DisplayMessageActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
Addendum:
I tried to include missing libraries, and now most of the errors turned into a grey 'X' (which, I guess, is now a mere warning and can be ignored? Should it be fixed? If so, how?)
The error regarding fragment_display_message stays as error, probably it is not defined (contrary to the example given.)
I was working my way through the same tutorial and I ran in to many of the same issues as you. One in particular had me stumped for an hour. I finally figured it out and here you go.
The error that the both of us got was the following:
fragment_display_message cannot be resolved or is not a type (line 62).
The fix is relatively simple, the reference to fragment_display_message should get changed to activity_display_message. Your new line in DisplayMessageActivity should now look like this:
View rootView = inflater.inflate(R.layout.activity_display_message, container, false);
I'm stuck when Add libraries in my project in Eclipse. I am following this link official android development website http://developer.android.com/tools/support-library/setup.html#libs-with-res and I do exactly what it says but I get errors for some reason.Here how it happends:
1.I download support libraries from SDK Manager.
2.I import them with existing Android Code into workspace and I press on the both .jar files Build Path>Add to Build Path.
3. Then on that project (made in step 2) I configure Build Path and I check both .jar files and uncheck the Android Dependencies and I click finish. Everything is okay for now.
But here comes the main problem=>
4. I press on my main project (myfirstapp) properties and click Add and select the libraries after that I press Apply and lots of errors raise up like R cannot be resolved to do variable and my R.id from /gen folder suddenly dissapear
I add now some screen shoots to make it better for you.
Sorry I have no reputations for posting images. Please copy links below
first image
second image
third image
fourth image
All my Codes: MainActivity.xml
package com.example.myfirstapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
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 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);
}
/**
* 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_main, container, false);
return rootView;
}
}
}
fragment_main.xml
<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"
android:orientation="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">myfirstapp</string>
<string name="action_settings">Settings</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
<string name="title_activity_displaymessageactivity">Displaymessageactivity</string>
<string name="hello_world">Hello world!</string>
</resources>
Displaymessageactivity.xml
package com.example.myfirstapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Displaymessageactivity extends ActionBarActivity {
#Override
public 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 = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.displaymessageactivity, 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_displaymessageactivity, container, false);
return rootView;
}
}
}
fragment_displaymessageactivity.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.myfirstapp.Displaymessageactivity$PlaceholderFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
Things I have tried so far:
1. Reinstall Eclipse and Java
2. Redownload libraries from SDK Manager
3. Clean the Project.
4. Make all my xml files starting with lowercase (but the MainActivity.xml and Displaymessageactivity.xml must start with uppercase)
I tried my best and I am stuck here forever. I am very frustated from Google :/
Every help is very appreciated and welcome!
Add the library to your application project:
In the Project Explorer, right-click your project and select Properties.
In the category panel on the left side of the dialog, select Android.
In the Library pane, click the Add button.
In step 3, notice that in the Library pane, you should see that the appcompat_v7 already be added (it's added automatically when you create your project follow MyFirstApp instruction, because you have already chosen minSdkVersion=8, not 11) (your second image).
So remove all the added libraries in the Library pane before adding your library (so in your third image it only has android-support-v7-appcompat in Library Pane), then the R.java will not disappear.
I'm very new to Android Development and I'd like to add a page to another dynamically. I'm a C# web developer and would like to do the same as using a Master Page and inserting other pages in this page.
The code I have at the moment is as follow: (Keep in mind that I've never done this, and any and all advise would be appreciated.)
I Have 3 main documents I'm working on at the moment:
Pharma Manifest.xml
MainActivity.java
fragment_main_dummy.xml(I'm using the dummy since it's already doing what I want.)
Here is the content on MainActivity.xml
package com.pharma.pharma;
import org.w3c.dom.Text;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.location.Address;
import android.os.Bundle;
import android.content.Context;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements
ActionBar.OnNavigationListener {
/**
* The serialization (saved instance state) Bundle key representing the
* current dropdown position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Set up the dropdown list navigation in the action bar.
actionBar.setListNavigationCallbacks(
// Specify a SpinnerAdapter to populate the dropdown list.
new ArrayAdapter<String>(getActionBarThemedContextCompat(),
android.R.layout.simple_list_item_1,
android.R.id.text1, new String[] {
getString(R.string.title_Dashboard),
getString(R.string.title_Customers),
getString(R.string.title_Products),
getString(R.string.title_Detailing),
getString(R.string.title_Appointments),
getString(R.string.title_Events), }), this);
}
/**
* Backward-compatible version of {#link ActionBar#getThemedContext()} that
* simply returns the {#link android.app.Activity} if
* <code>getThemedContext</code> is unavailable.
*/
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private Context getActionBarThemedContextCompat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return getActionBar().getThemedContext();
} else {
return this;
}
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current dropdown position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
#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 onNavigationItemSelected(int position, long id) {
// When the given dropdown item is selected, show its contents in the
// container view.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment).commit();
return true;
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
switch(getArguments().getInt(ARG_SECTION_NUMBER)){
case 1:
dummyTextView.setText("blah Blah Dashboard");
break;
case 2:
dummyTextView.setText("blah Blah Customers");
break;
case 3:
dummyTextView.setText("blah Blah Products");
break;
case 4:
dummyTextView.setText("blah Blah Detailing");
break;
case 5:
dummyTextView.setText("blah Blah Appointments");
break;
case 6:
//Insert XML to fragment dummy here as a test
break;
default:
//throw error
}
return rootView;
}
}
}
Here is the code in the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pharma.pharma"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.pharma.pharma.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
And lastly the code for fragment_main_dummy.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity$DummySectionFragment" >
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="true" />
<include
android:id="#+id/section_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
layout="#layout/dashboard" />
</RelativeLayout>
I've sat with this for days.
I'm still new at this and can't figure it out. I'm also pressured to get this whole project done in about a months time. Any help would be greatly appreciated.
Your title is conceptually wrong, you don't one XML to another. Those XML are heavily crunched and pre-compiled during the compile time and don't exist as you see them in the final app.
Further, those XML are just representations for the system to build Views and inside ViewGroups which is a class that extends View you can call .addView(view);
The include xml code you use, is a good way to re-use static generated XML, but for dynamic generated stuff you need to do it via code.
I've notice you're using fragments stuff. So probably you're better use the Fragment route of dynamically adding/removing stuff
The code you created inside onNavigationItemSelected is pretty much everything you need to do to dynamically change stuff around.
The fragment you're creating/instantiating will override onCreateView to inflate a new View and return it. That new view will be inserted on android.R.id.content (that is the View ID for your whole content) or for any ID that you specified in your XML.
hope it helps.
You could use LayoutInflater to do that.
eg.
RelativeLayout relativeLayout= (RelativeLayout) findViewById(R.id.relativeLayout);
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
relativeLayout.addView(childIndex, layoutInflater.inflate(R.layout.newLayoutToAdd, this, false) );