【问题标题】:How to use setOnClickListener and setOnTouchListener + for如何使用 setOnClickListener 和 setOnTouchListener + for
【发布时间】:2014-08-10 00:08:26
【问题描述】:

为什么我不能在我的程序中使用 setOnClickListener 和 setOnTouchListener? OnTouchListener 运行良好,但我无法运行新活动? 我做错了什么?

for (final ShopCategory category : gallery.getShopCategories()) {
            final Button button = new Button(this);

// ...等

button.setOnClickListener(new OnClickListener() {                   
                @Override
                public void onClick(View v) {
                    runNewActivity(gallery.getShops(), category);
                }
            });

            button.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN ) {

                        button.setTextColor(Color.parseColor("#333333"));
                        button.setBackgroundColor(Color.parseColor("#ffcc33"));             
                        return true;
                    } 
                     else if (event.getAction() == MotionEvent.ACTION_UP ) {
                         button.setTextColor(Color.WHITE);
                         button.setBackgroundColor(Color.parseColor("#333333"));                         

                     } 


                    return false;
                }
            }); 
categoriesButtonsLL.addView(button);

【问题讨论】:

    标签: java android onclicklistener ontouchlistener


    【解决方案1】:

    您可以通过使用可绘制选择器来更改按钮的显示状态而不是监听触摸事件来做得更好。 (在 res/drawable 中创建一个选择器 xml 文件,例如“button_bg.xml”):

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true"
           android:drawable="@drawable/button_pressed" /> <!-- pressed -->
        <item android:state_focused="true"
           android:drawable="@drawable/button_focused" /> <!-- focused -->
        <item android:drawable="@drawable/button_normal" /> <!-- default -->
    </selector>
    

    现在像这样编辑您的代码:

    for (final ShopCategory category : gallery.getShopCategories()) {
            final Button button = new Button(this);
            button.setOnClickListener(new OnClickListener() {                   
                @Override
                public void onClick(View v) {
                    runNewActivity(gallery.getShops(), category);
                }
            });
            button.setBackgroundResource(R.drawable.button_bg);
            categoriesButtonsLL.addView(button);
    }
    

    【讨论】:

      【解决方案2】:

      在这里快速猜测。但请尝试在您的 onTouch 中返回 false。在 ActionDown 中返回 true 意味着您已经处理了该事件,无需进一步处理。因此,如果处理了 ActionDown,则永远不会发生 onClick。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-02
        • 2016-08-27
        • 1970-01-01
        • 2013-12-26
        相关资源
        最近更新 更多