Accessing View inside the LinearLayout with code
I have a linearlayout ho开发者_C百科w can i access view inside this layout with the help of programming.
Sure, say if you have a LineraLayout linearLayout
, and in its xml you have a TextView
like
<LinearLayout [...]>
<TextView android:id="@+id/textView" [...] />
</LinearLayout>
then you can access that TextView
by
final TextView txt = (TextView)linearLayout.findViewById(R.id.textView);
Here you have your LinearLayout defined in an xml resource file.
You must assign an id
attribute to your TextView
for that to be accessible from your code directly. For this purpose stands there the android:id="@+id/textView"
.
In the xml file you will need to give the view an id..
android:id="@+id/someRandomID"
Then within your main java file you add this:
LinearLayout layout = (LinearLayout)findViewById(R.id.someRandomID);
(([TYPE]) findViewById(R.id.[NAME]))
For example, setting the text on a button:
((Button) findViewById(R.id.my_button)).setText("New text");
Assuming you have a linearlayout with id "linear1" and within that layout you have a ImageView with id "image1", you can do the following in your onCreate method in your activity class:
public void onCreate(Bundle bundle)
{
setContentView(R.layout.linear1);
ImageView image = (ImageView) findViewById(R.id.image1);
}
This is a very simple example, assuming that you are setting linear1 as the main layout of your activity.
精彩评论