【发布时间】:2010-04-10 20:27:52
【问题描述】:
我有一个 SurfaceView,它占据了屏幕的一部分,还有一些底部的按钮。当按下按钮并且用户拖动时,我希望能够将图片(基于按钮)拖动到 SurfaceView 上并在那里绘制。
我希望能够使用 clickListeners 等,而不仅仅是拥有一个巨大的 SurfaceView 和我编写代码来检测用户按下的位置以及它是否是一个按钮等。
我有一些解决方案,但对我来说似乎有点小题大做。智能地使用框架完成此任务的最佳方法是什么?
我的 XML 的一部分:
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background">
<!-- Place buttons along the bottom -->
<RelativeLayout android:id="@+id/bottom_bar"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:layout_alignParentBottom="true"
android:background="@null">
<ImageButton android:id="@+id/btn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="@null"
android:src="@drawable/btn_1">
</ImageButton>
<!-- More buttons here... -->
</RelativeLayout>
<!-- Place the SurfaceView in a frame so we can stack on top of it -->
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:layout_above="@id/bottom_bar">
<com.project.question.MySurfaceView
android:id="@+id/my_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</FrameLayout>
还有MySurfaceView中的相关Java代码,扩展了SurfaceView。在onDraw方法中使用mTouchX和Y来绘制图像:
@Override
public boolean onTouchEvent(MotionEvent event){
mTouchX = (int) event.getX();
mTouchY = (int) event.getY();
return true;
}
public void onButtonTouchEvent(MotionEvent event){
event.setLocation(event.getX(), event.getY() + mScreenHeight);
onTouchEvent(event);
}
最后是活动:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.my_surface);
mView = (MySurfaceView) findViewById(R.id.my_view);
mSurfaceHeight = mView.getHeight();
mBtn = (ImageButton) findViewById(R.id.btn_1);
mBtn.setOnTouchListener(mTouchListener);
}
OnTouchListener mTouchListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
int [] location = new int[2];
v.getLocationOnScreen(location);
event.setLocation(event.getX() + location[0], event.getY());
mView.onButtonTouchEvent(event);
return true;
}
};
奇怪的是,必须添加到活动中的 x 坐标,然后添加到视图中的 y 坐标。否则,它不会显示在正确的位置。如果不添加任何内容,使用 mTouchX 和 mTouchY 绘制的内容将显示在 SurfaceView 的左上角。
任何方向将不胜感激。如果我完全错误地处理这个问题,那也是很好的信息。
【问题讨论】:
标签: android android-widget android-layout