Android中自定义控件

本文介绍如何在Android应用中自定义控件,实现小球随手指移动的功能,通过主函数、自定义控件类及布局文件的配合,展示了一段简单但实用的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     Android中提供了许多种不同的控件,但是我们在开发中往往需要自己定义的控件,这时需要继承自View类,并重写其中相应的方法,实现自己的目的。

下面,实现的这个例子是在Activity上摆放一个小球控件,并能够跟随手指的移动而变换的不定的位置。

下面是实现的截图:


实现的代码也很简单,下面给出实现的代码:

1.主函数

package com.example.yourview;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		LinearLayout linearLayout=(LinearLayout)findViewById(R.id.layout);
		
		final MyView myView=new MyView(this);
		linearLayout.addView(myView);
		myView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				myView.currentX=event.getX();
				myView.currentY=event.getY();
				myView.invalidate();
				return true;
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

2.MyView类---自定义的控件实现类

package com.example.yourview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

@SuppressLint("DrawAllocation")
public class MyView extends View{
	public float currentX=40;
	public float currentY=50;

	public MyView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		Paint paint=new Paint();
		paint.setColor(Color.RED);
		canvas.drawCircle(currentX, currentX, 15, paint);
		
	}

}

3.布局文件

<LinearLayout 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"
    tools:context=".MainActivity" 
    android:id="@+id/layout"
    >

    

</LinearLayout>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值