第24章、OnLongClickListener长按事件(从零开始学Android)

小菜鸟战斗机 2018-3-27 188

在Android App应用中,OnLongClick事件表示长按2秒以上触发的事件,本章我们通过长按图像设置为墙纸来理解其具体用法。

  知识点:OnLongClickListener
  OnLongClickListener接口与之前介绍的OnClickListener接口原理基本相同,只是该接口为View长按事件的捕捉接口,即当长时间按下某个View时触发的事件,该接口对应的回调方法签名如下。
  public boolean onLongClick(View v) 
  参数v:参数v为事件源控件,当长时间按下此控件时才会触发该方法。
  返回值:该方法的返回值为一个boolean类型的变量,当返回true时,表示已经完整地处理了这个事件,并不希望其他的回调方法再次进行处理;当返回false时,表示并没有完全处理完该事件,更希望其他方法继续对其进行处理。

  

一、设计界面

  1、首先把a.jpg、b.jpg、c.jpg、d.jpg、e.jpg、prov.png、next.png图片复制到res/drawable-hdpi文件夹内。

  

  2、打开“res/layout/activity_main.xml”文件,生成ImageButton按钮。

  (1)从工具栏向activity拖出1个图像ImageView、2个图像按钮ImageButton。该控件来自Image&Media。

  

  3、打开activity_main.xml文件。

  我们把自动生成的代码修改成如下代码,具体为:

  (1)ImageView的id修改为picture;

  (2)“上一幅”按钮ImageButton的id修改为prov;

  (3)设置android:padding="0dp",按钮灰色边框去掉。

  (4)“下一幅”按钮ImageButton的id修改为next;

  (5)设置android:padding="0dp",按钮灰色边框去掉。

  

  代码如下:

[html] view plain copy
  1. <RelativeLayout   
  2.     xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     tools:context=".MainActivity" >  
  7.   
  8.     <ImageView  
  9.         android:id="@+id/picture"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:layout_alignParentTop="true"  
  13.         android:layout_centerHorizontal="true"  
  14.         android:layout_marginTop="18dp"  
  15.         android:src="@drawable/a"  
  16.         tools:ignore="ContentDescription" />  
  17.   
  18.     <ImageButton  
  19.         android:id="@+id/prov"  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"  
  22.         android:layout_alignParentLeft="true"  
  23.         android:layout_below="@+id/picture"  
  24.         android:layout_marginLeft="38dp"  
  25.         android:layout_marginTop="16dp"  
  26.         android:padding="0dp"  
  27.         android:src="@drawable/prov" />  
  28.   
  29.     <ImageButton  
  30.         android:id="@+id/next"  
  31.         android:layout_width="wrap_content"  
  32.         android:layout_height="wrap_content"  
  33.         android:layout_alignParentRight="true"  
  34.         android:layout_alignTop="@+id/prov"  
  35.         android:layout_marginRight="24dp"  
  36.         android:padding="0dp"  
  37.         android:src="@drawable/next" />  
  38.   
  39. </RelativeLayout>  


  4、界面如下:

  


最新回复 (0)
返回