接下来的这个小例子演示当手指在触摸屏上拖动的时候,一个红色的小球更随手指进行移动。不过这个例子大致演示了一下自定义UI组件。
先来看看效果吧:
代码大致如下:
AndroidDemoActivity.java
package Android.Demo; import android.app.Activity; import android.os.Bundle; import android.provider.ContactsContract.CommonDataKinds.Event; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.LinearLayout; public class AndroidDemoActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LinearLayout layout = (LinearLayout) findViewById(R.id.root); final DrawView draw = new DrawView(this); draw.setMinimumHeight(300); draw.setMinimumWidth(300); draw.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent evnet) { // TODO Auto-generated method stub draw.currentX = evnet.getX(); draw.currentY = evnet.getY(); draw.invalidate(); return false; } }); layout.addView(draw); } }
DrawView.java代码如下:
package Android.Demo; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.View; public class DrawView extends View { public DrawView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint p = new Paint(); p.setColor(Color.RED); canvas.drawCircle(currentX, currentY, 15, p); } public float currentX = 40; public float currentY = 40; }
main.xml代码如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/root" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > </LinearLayout>
时间: 2024-11-02 17:11:05