Android uses XML and Java to compose the UI

Source: Internet
Author: User

Illustrated with a simple picture browser instance


After the new project:

To add code in Activit_main.xml:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:id=" @+id/main "android:layout_width=" match_parent "android:layout_height=" Match_parent "Andro id:orientation= "Vertical" ></LinearLayout>

To add code in Java:

public class Mainactivity extends Activity {int[] image = new int[] {r.drawable.p1,r.drawable.p2,r.drawable.p3, R.drawable.p4};imageview Myimage;int curimage = 0; @Overrideprotected void onCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); LinearLayout layout = (linearlayout) This.findviewbyid (r.id.main); myimage = new ImageView (this); Layout.addview ( MyImage); Myimage.setimageresource (image[0]); Myimage.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method Stubmyimage.setimageresource (Image[++curimage%image.length]);});}


In Android, the nature of each component can be defined in. xml, and each property has a corresponding Java method

Note: The above code uses Java code to add a new component, can write the declaration in the class, but he must be assigned to a new in OnCreate () inside the object, or the program will be wrong, because it is necessary to add the component in Java when the parameter must be initialized (this)



This article is from the "Useless Uncle" blog, please be sure to keep this source http://aslonely.blog.51cto.com/6552465/1637277

Android uses XML and Java to compose the UI

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.