管理整个ViewGroup中的触摸事件,甚至包括子视图(按钮等)



管理整个ViewGroup中的触摸事件

Here Activity.java code

@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 - layout代码

<?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上的触摸事件(在这种情况下显示坐标)?

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;
    }
}

最新更新