初次学习android 如有不足之处希望大家指正
?
layout 下布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/root" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > </LinearLayout>
?自定义View 类
package com.android.imagebrowser;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 DrawView extends View { public float currentX = 40; public float currentY = 50; // 定义创建画笔 Paint p = new Paint(); public DrawView(Context context) { super(context); } public DrawView(Context context, AttributeSet set) { super(context,set); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 设置画笔的颜色 p.setColor(Color.RED); // 绘制一个小园(作为小球) canvas.drawCircle(currentX, currentY, 15, p); } // 为该组件的触发事件重写事件处理方法 @Override public boolean onTouchEvent(MotionEvent event) { // 修改currentX currentY currentX = event.getX(); currentY = event.getY(); // 通知当前组件重绘自己 invalidate(); // 返回true 表明该处理方法已经处理该事件 return true; }}
?
MainActivity
package com.android.imagebrowser;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.ImageView;import android.widget.LinearLayout;public class MainActivity extends Activity { // 定义图片数组 static int [] images = new int[] {R.drawable.four, R.drawable.two, R.drawable.three, }; // 当前图片 static int currentImg = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 获取LinearLayout 布局管理器 LinearLayout root = (LinearLayout) findViewById(R.id.root); final DrawView draw = new DrawView(this); draw.setMinimumHeight(500); draw.setMinimumWidth(300); root.addView(draw); } @Override public 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; }}
?