Android 使用xml和java混合編寫ui

來源:互聯網
上載者:User

標籤:android   ui   

以一個簡單的圖片瀏覽器執行個體說明


建立工程後:

    在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"    android:orientation="vertical" ></LinearLayout>

在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]);}});}


在Android中,每一個組件的性質可以在.xml中定義,同時每個性質都有對應的java方法

注意:以上代碼中 使用java代碼添加新的組件,可把聲明寫在類中,但是他必須被賦值為一個new在onCreate()內部的對象,否則程式會出錯,究其原因是因為在java中添加組件的時候必須初始化的時候加入參數(this)



本文出自 “無用大叔” 部落格,請務必保留此出處http://aslonely.blog.51cto.com/6552465/1637277

Android 使用xml和java混合編寫ui

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.