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>