管理整个ViewGroup中的触摸事件,即使是子项(按钮等)

时间:2016-06-30 08:57:30

标签: android touch ontouchlistener

管理整个ViewGroup中的触摸事件

这里是Activity.java代码

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final TextView textView = (TextView)findViewById(R.id.textView);
    // this is the view on which you will listen for touch events
    final View touchView = findViewById(R.id.ll);
    touchView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            textView.setText("Touch coordinates : " + String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
            return true;
        }
    });
}

layout / activity_main.xml - 布局代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/ll"
android:orientation="vertical">

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button"
    android:layout_weight="0.50" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/textView2"
    android:layout_weight="0.50" />

<TextView
    android:id="@+id/textView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Hello World, TestActivity" />
</LinearLayout>

如何管理按钮@+id/button上的触摸事件(在本例中为显示坐标)?

1 个答案:

答案 0 :(得分:-2)

public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
    Button btn;
    TextView textView;
    View touchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button);
        btn.setOnTouchListener(this);
        textView = (TextView) findViewById(R.id.textView);
        touchView = (View) findViewById(R.id.ll);
        touchView.setOnTouchListener(this);
    }
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        textView.setText("Touch coordinates : " + String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
        return true;
    }
}