实例:动态生成View控件例子---小球跟随手指滑动
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实例:动态生成View控件例子---小球跟随手指滑动相关的知识,希望对你有一定的参考价值。
package mydefault.packge; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.View.OnTouchListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.ToggleButton; public class MainActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); //布局管理器 LinearLayout layout = new LinearLayout(MainActivity.this); TextView tv = new TextView(MainActivity.this); tv.setText("这是代码生成的TextView"); Button button = new Button(MainActivity.this); ToggleButton tbtn = new ToggleButton(MainActivity.this); /////////////////////////////////////////////// //设置标题方法 button.setText("动态生成的按钮"); //设置布局方法 button.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)); //设置背景 button.setBackgroundColor(Color.CYAN); //------------ tbtn.setTextOff("关机"); layout.addView(tbtn); layout.addView(tv); layout.addView(button); //layout.addView(new myView(MainActivity.this)); this.setContentView(layout); } public class myView extends View implements OnTouchListener{ private float x; private float y; private Paint panter; public myView(Context context) { super(context); x = 0; y = 0; panter = new Paint(); this.setOnTouchListener(this); } ///////////////////////////// @Override public void draw(Canvas canvas) { super.draw(canvas); panter.setColor(Color.RED); canvas.drawCircle(x, y, 45, panter); } /* @Override public boolean onTouchEvent(MotionEvent event) { x = event.getX(); y = event.getY(); invalidate(); return super.onTouchEvent(event); }*/ @Override public boolean onTouch(View arg0, MotionEvent event) { x = event.getX(); y = event.getY(); invalidate(); return true; } } }
相关图片:
以上是关于实例:动态生成View控件例子---小球跟随手指滑动的主要内容,如果未能解决你的问题,请参考以下文章