在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",按钮灰色边框去掉。
代码如下:
- <RelativeLayout
- 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" >
-
- <ImageView
- android:id="@+id/picture"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentTop="true"
- android:layout_centerHorizontal="true"
- android:layout_marginTop="18dp"
- android:src="@drawable/a"
- tools:ignore="ContentDescription" />
-
- <ImageButton
- android:id="@+id/prov"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/picture"
- android:layout_marginLeft="38dp"
- android:layout_marginTop="16dp"
- android:padding="0dp"
- android:src="@drawable/prov" />
-
- <ImageButton
- android:id="@+id/next"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:layout_alignTop="@+id/prov"
- android:layout_marginRight="24dp"
- android:padding="0dp"
- android:src="@drawable/next" />
-
- </RelativeLayout>
4、界面如下: