Android自訂控制項實現及其布局
Android自訂控制項一般要繼承View類,因此控制項的實現及其相應的布局需要完成:
1. 繼承View類,並實現參數為(Context context,AttributeSet attrs)的建構函式
2. 在布局檔案xml中設定屬性的時候,應以(<包名.類名 />)的格式進行。
3. 聲明一個自訂控制項的變數,用findViewById將其與布局檔案關聯起來。
舉例:以下是自訂的MyView控制項,用於顯示2張圖片;
MyView.java代碼
[java]
package com.example.njupt.zhb.myselfview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
public Bitmap bitmap1=null;
public Bitmap bitmap2=null;
public int myInterval=10;
/*一定要重寫這個構造方法*/
public MyView(Context context,AttributeSet attrs) {
super(context,attrs);
}
/*重寫onDraw()*/
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int myViewWidth=getWidth()-myInterval*2;
int myViewHeight=getHeight()-myInterval;
int lessLen=myViewWidth/2<myViewHeight?myViewWidth/2:myViewHeight;
/*畫位元影像1*/
if (bitmap1!=null) {
RectF dst1=new RectF(0,myInterval,lessLen,lessLen+myInterval);
canvas.drawBitmap(bitmap1, null, dst1, null);
}
/*畫位元影像2*/
if(bitmap2!=null){
RectF dst2=new RectF(lessLen+myInterval*2,myInterval,lessLen*2+myInterval*2,lessLen+myInterval);
canvas.drawBitmap(bitmap2, null, dst2, null);
}
}
}
MainActivity.java代碼
[java]
package com.example.njupt.zhb.myselfview;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
public class MainActivity extends Activity {
MyView myView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("自訂MyView");
Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.lenna);
myView=(MyView)findViewById(R.id.myview);
myView.bitmap1=bitmap;
myView.bitmap2=bitmap;
}
}
activity_main.xml代碼
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.example.njupt.zhb.myselfview.MyView
android:id="@+id/myview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
AndroidManifest.xml代碼
[html]
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.njupt.zhb.myselfview"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:screenOrientation="landscape"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>