使用xml和java程式碼混合控制UI介面
main.xml....................
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background"
android:id="@+id/layout"
>
</LinearLayout>
activi..............................
package com.example.ui;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
private ImageView [] img=new ImageView[4]; //宣告儲存一個ImageView元件的陣列
private int[] imagePath=new int[]{ //宣告並初始化一個儲存訪問圖片的陣列
R.drawable.j1,R.drawable.j2,R.drawable.j3,R.drawable.w1
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout=(LinearLayout)findViewById(R.id.layout);//獲取個xml檔案中定義的線性佈局管理器
for(int i=0;i<imagePath.length;i++){//
img[i]=new ImageView(this);//建立一個ImageView元件
img[i].setImageResource(imagePath[i]);//為ImageView元件指定要顯示的圖片
img[i].setPadding(5, 5,5, 5);//設定ImageView元件的內邊距
LayoutParams params=new LayoutParams(253,148);//設定圖片的寬度和高度
img[i].setLayoutParams(params);//為ImageView元件設定佈局引數
layout.addView(img[i]);//將ImageView元件新增到佈局管理器中
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
效果如下圖: