自定义View类
通过自定义View类,可以自定义复杂的,按照自己需求的控件。
一个简单的例子
mainActivity.java 这个里面就是最普通的代码,但是给自定义的控件加上了一个onclick的时间
package com.example.test.com; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); MyView myView = (MyView) findViewById(R.id.myView); myView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.d("asdasd", ":asdasdasd"); } }); } }
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="700dp" android:layout_height="300dp" android:orientation="horizontal" android:padding="10dp" > <!-- 自定义View --> <com.example.test.com.MyView android:id="@+id/myView" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </RelativeLayout>
MyView.java
package com.example.test.com; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; public class MyView extends View { private Paint mPaint; public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); setFocusable(true); setClickable(true); //设置是否能点击 } /** * 通过canvas 画控件 */ @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); mPaint = new Paint(); //设置画笔颜色 mPaint.setColor(Color.RED); //设置填充 mPaint.setStyle(Style.FILL); //画一个矩形,前俩个是矩形左上角坐标,后面俩个是右下角坐标 canvas.drawRect(new Rect(10, 10, 100, 100), mPaint); mPaint.setColor(Color.BLUE); //绘制文字 canvas.drawText("Hello WORLD", 10, 110, mPaint); } }
结果: