How the view are refereed under MainActivity In android - android

Here is the XML code for a simple TextView:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
android:id="#+id/test"/>
Then, in MainActivity, it is used like this:
TextView test = (TextView) findViewById(R.id.test);
test.setText("test");
I want to know how the view is accessed in Main class, which is defined in xml layout.
Can anyone explain how it happens?

how the view accessed in Main class
To be honest, i dont know the process in detail. Let me help you on what i know :
The Activity will search the layout XML in setContentView method.
After the layout has been found, we can use findViewById to link the instance (test - in your case) we created to the layout XML.
If the ID is found, the instance (Java) and XML will be linked.
Of course, you can do something like :
TextView test2 = new TextView(this);
Which means the instance is not must exist in XML.
Sorry English is not my native language.

On your Activity, you have:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
//...
}
According to Android documentation, setContentView is responsible for linking your XML layout to your Activity:
Set the activity content to an explicit view. This view is placed
directly into the activity's view hierarchy. It can itself be a
complex view hierarchy.
After the Activity's content view is set, you can use findViewById in order to access the views of the XML linked to your Activity:
Finds a view that was identified by the id attribute from the XML that
was processed in onCreate(Bundle).
Hope it helps you to understand this process! :)

I think this is the method
1.when you create or declare a text view or something like that a reference is generated in your R file(JAVA file).
2.which is what you access through
R.id.test
this is how your linking works

Related

findViewById from specific layout seems not linked

Good evening
I am trying to make users can change font in other layout called row.XML from the main activity class everything seems okay but there's no change of the font or color it seems like look not linking
Any idea guys
Edit:
I used include method row.XML in main XML but all in vain
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view;
/* We inflate the xml which gives us a view */
view = inflater.inflate(R.layout.row, null);
/* Get the widget with id name which is defined in the xml of the row */
textfont = (TextView) view.findViewById(R.id.textItemmain);
(https://i.stack.imgur.com/GN6UQ.png)
That is not how views work, views are not explicitly bound to an activity so all you are doing by inflating that view is inflating a view that isn't associated to anything.
To send data back to an activity you need to use startActivityForResult then listen for data coming back to it when the activity is resumed
First of all you need to know that you can't change the views properties of another layout activity directly from your current activity it is not possible, what you can do is that before going to the next activity you can pass an intent with a Boolean flag that will be check in the targeted activity to see if a boolean condition is true or false if it is true change the font of textview in target activity if it is false dont do anything, This is the only way to achieve what you are trying to do. If you can't create an intent and pass boolean extra in it post in comments I'll update the answer.

Show View in all my app

I need show a TextView in all Activities, but is much work to do it one by one, because I have +10 Activities.
My objective is when I click in a button, show a textview ("Importing ...") at the bottom of the application. This textview will disappear when I receive a push notification, and I owe a pop up with the response (the pop up also has to appear in any activity).
My project has a custom abstract BaseActivity and all activities extends it.
public abstract class BaseActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void setActionBar(#IdRes int idResToolbar) {
Toolbar toolbar = (Toolbar) findViewById(idResToolbar);
setSupportActionBar(toolbar);
updateFont(toolbar);
}
// ...
}
I think I could use for my purpose but not how to do it.
If anyone has any suggestions I will be happy to hear it.
Thanks in advance.
Use fragments for your content (instead of different activites) you then can add global views to the activity, which holds the fragments.
If you don't want to do that, you'd have to modify the layout(s) in your Base class.
I would suggest you to use a PopupWindow that contains the text view and create a separate class that initializes the PopupWindow on the basis of context given to it.
Now in all your Activities you will have the control of showing and hiding the window as you want. Make sure to make all utility methods required in the separate class to avoid coherence for example hiding and showing the window. setting text of text view of the window and etc.
You can write in onCreate() of your base activity something like
setContentView(R.layout.base_layout);
And in every other Activity at start of onCreate() method, just use super.onCreate()
And more than that to support different layouts add something like this in onCreate() (example for one of activities)
LayoutInflater inflater = getLayoutInflater();
inflater.inflate(R.layout.activity_1_layout,rootGroup)
where rootGroup is a ViewGroup in your Base Activity, in which you will add additional components for every other activity
Create a service, which creates a View which can be drawn over other apps (will require the relevant permission in the manifest)
You could use one of the open source libraries available like this or refer to this example
It's better you use fragments instead of using many activities. However, if you don't wanna do so, I suggest you create a factory which will generate a textview to all activities. Then you must add it into each activity's view.

NullPointerException when calling setText on a TextView outside activity_main.xml

I am making an app using two tabs with different layouts, which means I have three total layouts at the moment:
activity_main,
fragment_receive,
fragment_send
In my onCreate method in my main activity, the following line sets my content view to activity_main. (If anyone could explain why this layout appears to be blank and yet my app still shows both tabs, that would be great.)
setContentView(R.layout.activity_main);
Then I use the findViewById method to set a TextView to a view that appears in both fragment_receive.xml and fragment_send.xml.
currentExchangeRate = (TextView) findViewById(R.id.exchangeRateView);
Then I attempt to use the setText method on this TextView.
currentExchangeRate.setText(Double.toString(lastPrice));
This line gives me the NullPointerException.
Can anyone explain this to me?
findViewById() called from the Activity, looks for the id in the hierarchy of views of the Activity.
if you want to perform that on the Fragment hierarchy, you have to call it from the Fragment view, for example view.findByById() from the Fragment onCreateView, after you inflated the layout.
When you call:
currentExchangeRate = (TextView) findViewById(R.id.exchangeRateView);
The compiler finds that the static int ID does exist within your R.id because you declared them in your fragments, and therefore doesn't throw a compiler error. But at runtime, the current view layout (the one you set with setContentView(R.layout.activity_main);) doesn't hold that ID and therefore returns null.
To access your textview that exists within your Fragment from the Controlling Activity, you use the Fragment Manager (add an id property to your fragments in activity xml, or set tags when you declare your Fragments in your code):
ReceiveFragment receiveFragment = (ReceiveFragment) getSupportFragmentManager().findFragmentById(R.id.receive_fragment);
TextView tv = (TextView) receiveFragment.getView().findViewById(R.id.exchangeRateView);
tv.setText(Double.toString(lastPrice));
findViewById retrieves the view with the requested id from your activity's layout
To get your fragment's textview, make the view that your fragments onCreateView is returning a static variable and initialize it in the onCreateView.
Then you can retrieve the textview like this:
TextView textview = (TextView) YourFragmentTitle.yourFragmentViewTitle.findViewById(R.id.yourId);

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.

Object created from layout xml file is null

I have two classes that extend the activity class. Each class has it's own layout class, main.xml and compose.xml.
In my main activity I try to access a layout element that is in compose.xml. So:
EditText smsBody = (EditText)findViewById(R.id.smsBody);
But smsBody is null. Why? How can I access it?
Did you set the content view in the onCreate() method?
Like in this example:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Well, your main activity has a main.xml layout. Your compose activity has a compose.xml layout. Assuming your "smsBody" EditText is in the compose.xml layout, then this will be only accesible in your compose activity, since that widget doesn't exist in your main.xml layout.
when main activity have layout main.xml, how you can expect that you can access component of compose.xml ?? you suppose to play with view inside layout you set using setContentView() .
in exceptional cases we need to use other layouts as well , so you can use LayoutInflater for this

Categories

Resources