<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.mint.recordvideo.MainActivity">
<com.example.mint.recordvideo.mySurfaceRecord
android:id="@+id/myview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" /> <Button
android:id="@+id/button_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="stopMyView" />
</RelativeLayout>
該例子會創造(new)出兩個物件實體(instance),一個是自行定義的類型mySurfaceRecord,自行定義的類型(class)務必要給冠上package名稱,否則執行時鐵定出錯!它是繼承自SurfaceView而來,另外一個是Android系統的內建Button類型,java程式透過findViewById(R.id.button_stop)就可以找到Button的實體(instance).按鍵類型必須放在後面才不會被SurfaceView 擋住看不見,底下是主程式: MainActivity.java:package com.example.mint.recordvideo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button;public class MainActivity extends AppCompatActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button quitButton = (Button) findViewById(R.id.button_stop); quitButton.setText("結束"); } public void stopMyView(View v){ finish(); } }底下是自行定義的類型:mySurfaceRecord.java,須注意的是自行定義類型mySurfaceRecord的建構式必須要定兩個參 數Context 及 AttributeSet,
否則執行時就會出錯!package com.example.mint.recordvideo; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; public class mySurfaceRecord extends SurfaceView implements SurfaceHolder.Callback {private SurfaceHolder holder;private Context ctx;public mySurfaceRecord(Context context, AttributeSet attrs) { super(context); initMyView(context); }public void initMyView(context){
ctx = context; // 保存 context 備用holder = getHolder(); // 獲取把柄,備用 holder.addCallback(this);// 加入 callback// ...
}
@Override
public void surfaceCreated(SurfaceHolder holder){ // ... }
@Override
public void surfaceDestroyed(SurfaceHolder holder){
// ...}@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){// ...}}
沒有留言:
張貼留言