Android – Using TouchDelegate

扩大按钮触摸区域
本文介绍如何使用Android中的TouchDelegate来增加按钮的触摸区域,通过一个简单的示例展示了如何设置TouchDelegate,使用户更容易点击到目标按钮。

      TouchDelegates in Android allow to increase the touch area of a View, e.g. Button. This is very useful if you want to make it easier for the user to touch your button.

      Here is a small example for the usage of a touch delegate. The layout has the ID root and contains a button with the ID delegated_button.

      

kage de.vogella.android.touchdelegate;
 
import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.TouchDelegate;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends Activity {
    private Button mButton;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mButton = (Button) findViewById(R.id.delegated_button);
        View parent = findViewById(R.id.root);
        parent.post(new Runnable() {
            public void run() {
                // Post in the parent's message queue to make sure the parent
                // lays out its children before we call getHitRect()
                Rect delegateArea = new Rect();
                Button delegate = mButton;
                delegate.getHitRect(delegateArea);
                delegateArea.top -= 600;
                delegateArea.bottom += 600;
                delegateArea.left -= 600;
                delegateArea.right += 600;
                TouchDelegate expandedArea = new TouchDelegate(delegateArea,
                        delegate);
                // give the delegate to an ancestor of the view we're
                // delegating the
                // area to
                if (View.class.isInstance(delegate.getParent())) {
                    ((View) delegate.getParent())
                            .setTouchDelegate(expandedArea);
                }
            };
        });
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值