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