画面の一部を占める 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>
そして、SurfaceView を拡張する MySurfaceView の関連する Java コード。mTouchX と Y は onDraw メソッドで画像を描画するために使用されます。
@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 の左上隅に表示されます。
どんな方向性でも大歓迎です。私がこれを完全に間違った方法で行っている場合、それも良い情報です。