自定义view组件
參考《瘋狂android講義》第2版 2.1節P48,對應CustomViewDemo.zip。
若在開發過程中,發現現有的view均不能滿足需要,可以自定義一個view。
自定義一個view 的關鍵在于重寫view類的幾個核心方法,如onDraw, onTouchEvent等。
自定義view類:
DrawBall.java
package com.ljh.customviewdemo.ui;import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View;public class DrawBall extends View {private Paint p = new Paint();private float currentX = 40;private float currentY = 50;public DrawBall(Context context) {super(context);}public DrawBall(Context context, AttributeSet set) {super(context, set);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);p.setColor(Color.RED);canvas.drawCircle(currentX, currentY, 15, p);}@Overridepublic boolean onTouchEvent(MotionEvent event) {currentX = event.getX();currentY = event.getY();/** Invalidate the whole view. If the view is visible,* onDraw(android.graphics.Canvas) will be called at some point in the* future. This must be called from a UI thread. To call from a non-UI* thread, call postInvalidate().*/invalidate();return true;}}Activity類:MainAtivity.java package com.ljh.customviewdemo;import android.os.Bundle; import android.app.Activity; import android.view.Menu;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}@Overridepublic 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;}}
布局文件:activity_main.xml <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=".MainActivity" ><!-- 注意:此處使用類的全路徑,標明ui類型。 --> <com.ljh.customviewdemo.ui.DrawBallandroid:layout_width="wrap_content"android:layout_height="wrap_content"/></RelativeLayout>
注意,activity中包括多個view。一個activity對應一個布局文件,布局文件中包括多個view,這些view可以是android定義好的,或者自定義的。
轉載于:https://www.cnblogs.com/eaglegeek/p/4557980.html
總結
- 上一篇: [JDK]找不到或无法加载主类 java
- 下一篇: java页面请求跑批处理sql的有关问题