2010年5月21日星期五

通過XML調用自定義視圖(Custom View)

前文"建立自定義視圖(Custom View)"通過程序代碼setContentView(myView)調用自定義視圖. 現在看看如何通過XML調用自定義視圖.

自定義視圖(Custom View)

- 繼續使用使用前文的MyView Class, 不需修改.

- 修改佈局文件main.xml
添加三個虛設的按鍵, 和一個自定義視圖.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 1"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 2"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 3"
/>
<view
class="com.AndroidView.MyView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>


- 修改onCreate()方法, 使用main設定佈局.
    public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//MyView myView = new MyView(this);
//setContentView(myView);
}



next: 處理自定義視圖的事件(Event)

1 則留言:

  1. 不好意思 我有參考了你的程式 但有出現一些狀況
    我把onCreate()方法, 使用main設定佈局. 他就會強制關閉耶
    可以幫我解答一下嗎謝謝

    回覆刪除