您的位置:首页 > 移动开发 > Android开发

android学习之-----使用TouchDelegate增大触摸面积

2016-10-13 15:06 441 查看

需求:

  有时候由于界面上图标过小 ,导致点击触摸的区域太小不好操作,或者有时候会发生误操作。

解决办法:

  如果是图片设置src属性,设置padding  ,或者外层嵌套一层布局 通过外层布局的点击事件来触发响应操作。
 总的来说主要还是需要增大可触摸的区域。
 
  TouchDelegate  

   官方解释:https://developer.android.com/reference/android/view/TouchDelegate.html

    xml代码:
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.mytestapp.MainActivity" >

<LinearLayout
android:id="@+id/llayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<ImageView
android:id="@+id/img"
android:layout_width="10dp"
android:layout_height="10dp"
android:src="@drawable/ic_launcher" />
</LinearLayout>

</RelativeLayout>


可以看见上面我们只设置了 图片的大小为10dp  应该是很小吧。

 java代码设置 

public class MainActivity extends Activity {
private LinearLayout llayout;
ImageView img;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.img);
llayout = (LinearLayout) findViewById(R.id.llayout);
llayout.post(new Runnable() {
@Override
public void run() {
llayout.setTouchDelegate(new TouchDelegate(
new Rect(0, 0, llayout.getMeasuredWidth()/2, llayout.getMeasuredHeight()), img));
}
});

img.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "1111", 0).show();
}
});

}

}


注意事项:外层需要有一个容器承载需要扩展的那个View 用外层的容器去调用setTouchDelegate方法 为子View扩展可以点击的范围大小。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: