Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 初級開發 >> Android中Widget的使用示例

Android中Widget的使用示例

編輯:初級開發

之前已經寫過通過重繪整個背景的方式,實現物體移動。今天要講的是,

如何通過移動widget,vIEw等控件,實現部分重繪。結合之前發Droiddraw工具,使用AbsoluteLayout,可以隨意放置控件在任何位置。

package com.sky;

import android.app.Activity;

import android.os.Bundle;

import android.vIEw.KeyEvent;

import android.vIEw.MotionEvent;

import android.view.VIEw;

import android.view.VIEw.OnClickListener;

import android.widget.AbsoluteLayout;

import android.widget.Button;

@SuppressWarnings("deprecation")

public class AbosoluteMove extends Activity implements OnClickListener

{

/** Called when the activity is first created. */

public Button button1;

public Button button2;

public Button button3;

public Button button4;

Button tmp;//臨時保存,選擇的BUTTON

int x;

int y;

int flag;//用於標志選擇哪個BUTTON

@Override

public void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentVIEw(R.layout.main);

button1=(Button) findVIEwById(R.id.widget27);

button2=(Button) findVIEwById(R.id.widget28);

button3=(Button) findVIEwById(R.id.widget29);

button4=(Button) findVIEwById(R.id.widget30);

button1.setOnClickListener(this);

button2.setOnClickListener(this);

button3.setOnClickListener(this);

button4.setOnClickListener(this);

}

@Override

public void onClick(VIEw v)

{

// TODO Auto-generated method stub

switch(v.getId())

{

case R.id.widget27:

flag=R.id.widget27;

setTitle("button1");

break;

case R.id.widget28:

flag=R.id.widget28;

setTitle("button2");

break;

case R.id.widget29:

flag=R.id.widget29;

setTitle("button3");

break;

case R.id.widget30:

flag=R.id.widget30;

setTitle("button4");

break;

}

}

@Override

public boolean onKeyDown(int keyCode, KeyEvent event)

{

// TODO Auto-generated method stub

return super.onKeyDown(keyCode, event);

}

@Override

public boolean onTouchEvent(MotionEvent event)

{

// TODO Auto-generated method stub

x = (int) event.getX();

y = (int) event.getY();

tmp=(Button) findVIEwById(flag);//獲取所選中的BUTTON

AbsoluteLayout.LayoutParams params1=new AbsoluteLayout.LayoutParams(50,50,x-25,y-50);

tmp.setLayoutParams(params1);//設置BUTTON的新位置

switch(event.getAction())

{

case MotionEvent.ACTION_DOWN:

tmp.invalidate();

tmp.setText("選中down");

break;

case MotionEvent.ACTION_UP:

tmp.invalidate();

tmp.setText("選中UP");

break;

case MotionEvent.ACTION_MOVE:

tmp.invalidate();

tmp.setText("選中move");

break;

}

return super.onTouchEvent(event);

}

}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved