【问题标题】:Android onTouch to handle multiple viewsAndroid onTouch 处理多个视图
【发布时间】:2014-09-18 01:27:50
【问题描述】:

我在 LinearLayout 中水平排列了三个 TextView。我想要做的是,当用户从第一个 TextView 开始触摸,通过第二个 TextView 按下,最后在第三个 TextView 结束触摸时,所有三个 TextView 都应该用不同的背景颜色突出显示。我最初是这样尝试的:

    final TextView tv1 = (TextView)findViewById(R.id.text1);
    tv1.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            tv1.setBackgroundColor(Color.YELLOW);
            return true;
        }
    });

    final TextView tv2 = (TextView)findViewById(R.id.text2);
    tv2.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            tv2.setBackgroundColor(Color.BLUE);
            return true;
        }
    });

    final TextView tv3 = (TextView)findViewById(R.id.text3);
    tv3.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            tv3.setBackgroundColor(Color.RED);
            return true;
        }
    });

但结果是所有的触摸,即使我正在 ACTION_MOVEing 到 TextView 2,onTouch() 也会在第一个 TextView 上调用。我想到实现这一点的唯一事情是将 OnTouchListener 附加到父布局,并且对于每个触摸事件,查看当前触摸事件是否在任何子 TextView 上,并更改该子的背景颜色(如果有)。但是我想知道android是否有一个API可以做到这一点,或者有什么聪明的方法可以做到这一点。

【问题讨论】:

  • 你能发布你的xml吗
  • 还有问题吗?
  • 直到现在我才检查这个问题。感谢您的回复,但我的代码是一个简单的演示。操作更复杂,我通过添加一个空白容器并处理该容器中的所有触摸事件来解决这个问题..

标签: android touch views drag


【解决方案1】:

您可以为每个文本视图使用选择器

android:background="@drawable/selector"

扇区可绘制

<?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/selected_state" />
</selector>

选定状态

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">
    <solid android:color="@color/required_color" />
</shape>

【讨论】:

    猜你喜欢
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多