Why can't I use setContentView(R.layout.main) in last line without setContentView(tv)? Please explain this to me.
package com.mue.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloWorldActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello, Android i am suvankar");
setContentView(tv);
}
}
You have to define the textview in the R.layout.main ( a xml file) this file contains the information of the objects in the activity.
if you are using eclipse you can simple drag and drop a textview, just open the main file.
(folder res -> layout -> main.xml)
then yo have to call it in your program:
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.tv); //<-- yo have to use the same ID that is in the main.xml file
and then you can set the text. all of this in the oncreate function.
tv.setText("Hello, Android i am suvankar");
Well, I hope I've helped. is my first response here
You shouldn't call setContentView() twice in your onCreate. Either call setContentView(R.layout.main) or call setContentView(tv) but not both. I would prefer the first of the two... but you need to make sure the TextView is declared in your layouts XML.
Lets first try to understand what setContentView() method does. Basically setContentView() places your UI on your Activity. Now to create a UI component for your Activity, you can either use xml resource (e.g. R.layout.main) or you can obtain an instance of the UI component in your code and dynamically add it to your Activity. For example
TextView tv = new TextView(this);
tv.setText("Hello, Android i am suvankar");
setContentView(tv);
In your case you created an instance of the TextView tv, set some text to it and added that to your Activity. Here you dont need to use setContentView(R.layout.main). However if you have a xml layout (main.xml) in your layouts folder like the following:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World"
/>
</LinearLayout>
and at the bottom of your application you write setContentView(R.layout.main), your should see a black screen with Hello World written on it. This is because here you created a TextView instance, set some text to it, but did not place it to your activity by calling
setContentView(tv), rather you added a completely different layout resource. If you use setContentView(tv) and at the end of your onCreate() you add setContentView(R.layout.main) then again you will see Hello World instead of "Hello, Android i am suvankar" because at the end you replaced your UI resource. However, if you forget to add your xml resource and call 'setContentView(R.layout.main)' compiler will issue an error for not finding the xml resource specified.
Related
I'm new to Android programming, and I'm trying to make a simple button which displays a toast notification when clicked.
I tried to initialize a button called "button" in my MainActivity like so:
public class MainActivity extends Activity implements View.OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button =(Button)findViewById(R.id.button1);
button.setOnClickListener(this);
}
public void onClick(View v){
Toast toast = Toast.makeText(this, "Click Me", Toast.LENGTH_LONG);
toast.show();
}
}
Also, here is 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">
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/button1">
</Button>
</RelativeLayout>
UPDATE: findViewById now works fine after importing android.R. However, this created a new error when I call setContentView(R.layout.activity_main);
Okay a bit of background here. strings.xml is for defining pieces of text. For instance the text that might go on a button (but this does not define the button itself).
The button is going to have to be defined in a layout file in the res/layout/ directory. Yours is likely called activity_main.xml.
You'll need to create a button element in this file and assign the id to something descriptive. This kind of id is what findViewById is going to search on.
An example:
<Button
android:id="#+id/thebuttonsid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="96dp"
android:text="#string/button1" />
You can get a handle to this button like so:
Button button = (Button)findViewById(R.id.thebuttonsid);
Notice how I set the text to #string/button1? This is what the strings.xml file is for. However the layout files in the layout directory are where you define controls like buttons.
The button's ID name is same to the button's text name. You'd better change any one to other name.It must be work.
I would clean the project and build again. Or reimport the project. Eclipse is ... just hard to use. Try to use Android Studio.
When there is some "mismatch" with resources cleaning a project is a good advice. IN the past it was even more so.
Next what I would check if your resources compile as such. You might have an error somewhere in your resources, therefore the R does net get compiled and any reference to R.id.* is not valid.
I'm having issues with understanding how I should organize my user interface in Android. My original plan was to create TextViews and ListViews programatically and change them when buttons are clicked, etc.
Here's my first simple attempt. viewFriends is a method within my Activity class. It's called when a menu button is pressed.
private void viewFriends()
{
mText = new TextView(this);
mText.setText("Gathering information...");
setContentView(mText);
...irrelevant code follows
Why doesn't this seemingly simple example work? How should I logically organize and manage my user interface objects (TextViews, ListViews, Buttons, etc).
Thanks.
The best work would be having those listviews and textviews in your XML files and give them a suitable ID like following:
<ListView
android:id="#+id/myList"
android:layout_width="wrap_content"
android:layout_weight="1"
/>
Just like above have your text view too in XML file an add the android:id attribute.
Once you define this way in your java file have references to them:
ListView myListObj = (ListView)findViewById(R.id.myList);
Now you have an object called myListObj in your java file and now you can do whatever you want to do with it.
:)
Let me if you find any issue in this so that I can update the answer to meet your specific need.
Don`t use setContentView in your method. Usually it should only be called once in the onCreate method of your activity.
Best predefine your bottons/TextViews in xml, get a handle for them (findViewbyId...)
and modify them that way.
If you create them programaticly, just add them to a view containter from your xml.
Like :
setContentView(R.layout.main);
Lets say in main.xml there is a LinearLayout with the id: root.
// get accces to that layout:
LinearLayout rootLayout = (LinearLayout) findViewById (R.id.root);
// create a new TextView
TextView tv1 = new TextView (this);
tv.setText("Hello!");
// add it to your base layout
rootLayout.addView(tv1);
// done! :)
Make a double check on what you are getting in "this".
change it to your java file name.this
You have to reload/refresh your activity once you change it.
Try this
#Override
protected void onResume() {
if(param.equalsIgnoreCase("gr"))
{
finish();
Intent myIntent = new Intent(yourActivity.this, yourActivity.class);
startActivity(myIntent);
}
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Why did it say hello world?");
setContentView(R.layout.main);
}
}
I'm following the Hello, World tutorial on the android SDK site. When I set the text for tv, it never shows. Instead, the output is:
Hello World, HelloAndroid!
Where in the world is that coming from? I never wrote that text, ever, anywhere...freaky.
TextView tv = new TextView(this); << create TextView object
tv.setText("Why did it say hello world?"); << set text to it
setContentView(R.layout.main); << display the view defined in main.xml
as scriptocalypse said you can simply set the content view to tv, alternatively, and I think a better approach is to use the main.xml:
in main.xml there is a TextView and it has a property called id, it looks something like this: <TextView android:id="#+id/text" you can use this id to get the TextView object of this xml like this:
setContentView(R.id.xml);
TextView tv = (TextView)findViewById(R.id.text);
tv.setText("Your text");
There are 3 things to remember:
R.id.text is corresponding to android:id="#+id/text".
R.id.text is an integer, generated during the build of application, it's not a string, and cannot be manipulated as a string.
setContentView has to be called before calling findViewById, otherwise, you will get null as return value of findViewById.
Check your main.xml file. It's likely being printed from there.
To get your own test there, add your new TextView to the main.xml
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Your text here" />
(Note: the "Your text here" should really be brought out to the strings.xml file.)
To put in an editable text field, use an EditText field.
<EditText android:id="#+id/TextId" android:hint="background text"
android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
You should use setContentView before creating a new TextView object. Also, did you remember to add the TextView to the display?
setContentView(tv)
I see you adding the xml layout, but you never add the newly created TextView
You are calling setContentView() and passing in a reference to a layout, specifically main.xml as noted by Haphazard. If you want to see your TextView that you just created, you should be able to pass the variable tv into the setContentView() method.
The default main.xml has a reference to a String in strings.xml in your res/ folder. In there is the definition of a String "Hello World", which is why you are seeing "Hello World".
I am trying to create a simple button example, but when I add this code:
mButton = (Button) findViewById(R.id.button1);
it wont update my R.id file. I've tried everything including making sure automatic build is on, cleaning the project, and updating the SDK. This happens in both 1.6 and 2.2 projects.
Here's what full code is looking like:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class NewTest extends Activity {
Button myButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton = (Button) findViewById(R.id.button1);
}
}
findViewById is looking at the R.id file for the location you refer to.
Your code will not cause the file to update as it is only looking for the button.
Creating the button in your layout will cause the R.id file to update.
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button One"/>
As you are using findViewById in context, and the view for the current context is main.xml, the above button example will need to be inside the main.xml file. Otherwise if you had another button with the same name in another .xml layout, the entry would be made in your R.id file but your code would give you a null pointer exception, because the button doesn't exist in the context you are trying to reference it from.
Make sure you have proper import for your app's R class in your Activity:
import your.app.package.R;
UPDATE: this implicit import is only needed if your Activity class is not in the root of your.app.package package.
Save your project before using R.id.something
Since you are using XML based Layout make sure that you have android:id attribute in the main.xml file with "#+id/button1" as its value.......
It wouldn't update the generated R.java file when you just refer to an existing id.
It only updates when you add a resource. button01 must already exist in one of your .xml files, otherwise your 'findViewById(R.id.button1)' wouldn't compile.
I had the same problem using API 19 with the layout editor set to API 15 while trying to follow the NotePadV1 tutorial. I couldn't get the R.id.text1 to compile from the notes_row.xml file.
Originally, I had just pasted text into the xml file to generate the layout. After unsuccessfully trying deleting R and a Clean, I tried deleting the notes_row layout entirely. When I recreated the layout, I used the graphical interface to add the properties of the TextView object, just the Id #+id/text1, width and height. Then I did a Clean and compile. It worked.
Is there anywhere that I can find documentation on the scope of the XML files? I have an app I am currently working on and have been struggling with getting a feature to work and it seems that the problem I am having is that I am trying to access an element in an XML file that must be out of scope. To simplify the layout, my project has main.xml, sub.xml, main.java, and sub.java files in it. As you can probably guess, main.java works with main.xml and sub.java is working with the elements in sub.xml. Here's where the issue comes in, I have a TextView element that is created in main.xml that I would like to modify the text in, but the action that would trigger it will occur in sub.java. I can't figure out how to change it from sub.java, and I can't figure out how to move the element into sub.xml. The code I am using is pretty simple:
TextView titleText = (TextView) findViewById(R.id.myTitle);
titleText.setText(filePath);
I get a FC every time I run the app, but if I move the code into main.java, it runs flawlessly. If anyone can offer any ideas, or point me in the direction of some documentation that would explain what java files can access what elements in which xml files, that would be awesome! Sorry for the novel, but I'm just struggling to get the point across. Thanks.
try like this Bryan in Main.xml file it works with no issue...........Declare first & then Initialize it...
public class Main extends Activity {
static TextView tv;
static Button submit;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
tv = (TextView) findViewById(R.id.header_text1);
}
}
Activity.findViewById(int) only works if that view is in the activity's layout. So no, you can't refer to a view in main.xml because that layout doesn't apply to sub.
Do you have any TextViews in sub.xml called myTitle?
You can access the the textview of main.java(main.xml) in submain.java as follows
In main.java write the following code
static TextView titleText = (TextView) findViewById(R.id.myTitle);
titleText.setText(filePath);
and u can access this submain.java as
Main.titleText.setText(filePath);