现在的位置: 首页 > 综合 > 正文

android ImageButton触屏实例

2013年12月12日 ⁄ 综合 ⁄ 共 1634字 ⁄ 字号 评论关闭

1、步骤1 利用内部类形式完成ImageButton绑定触屏监听,这里使用的监听器为OnTouchListener(触屏监听器)

 

2、步骤2 重写接口中的 onTouch(View v , MotionEvent event)抽象函数。onTouch(View v ,MotionEvent event)的参数说明如下

 

 第一个参数:表示触发触屏事件的事件源view;

 第二个参数:表示触屏事件的类型,如按下,抬起,移动

 

3、步骤2 利用MotionEvent.getAction()函数判断用户触发事件的类型。触发事件有两种类型:

 

MotionEvent.ACTION_DOWN:按下事件

MotionEvent.ACTION_UP:抬起事件

 

4、 步骤4 根据按下与抬起事件的不同,调用ImageButton类的setBackgroundDrawable()函数设置ImageButton背景图即可

源码:

 java代码:

 

package com.test;

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

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
	private ImageButton Ibtn;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Ibtn =(ImageButton)findViewById(R.id.imagebutton);
        //为图片按钮添加触屏监听
        Ibtn.setOnTouchListener(new OnTouchListener() {
        	public boolean onTouch(View v , MotionEvent event){
        		//用户当前为按下
        		if(event.getAction()==MotionEvent.ACTION_DOWN){
        			Ibtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.press));
        			//用户当前为抬起
        		}
        		else if(event.getAction()==MotionEvent.ACTION_UP){
        			Ibtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.nopress));
        		}
        		return false;
        	}
        });
    }
}

 布代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imagebutton"
        android:background="@drawable/nopress"
        />

</LinearLayout>

 

结果图

 

抱歉!评论已关闭.