【发布时间】:2015-09-22 19:18:07
【问题描述】:
我有 ReltiveLayout,里面有 ImageView 和 TextView。
所以我有两个事件监听器:
onClickonTouch
我正在使用9patch 作为图像。当我使用 onTouch 事件时,onClick 根本没有触发,而且 onTouch 也不是很好。如果我禁用 onTouch 并离开 onClick 它会触发并更改活动。我想让 onTouch 和 onClick 一起工作。我要:
- 当点击RelativeLayout时,它会显示选中的按钮ImageView
- 否则显示普通按钮ImageView
- onClickListener 更改活动。
这是我的代码:
StartBtn = (RelativeLayout) findViewById(R.id.StartBtn);
StartBtnImage = (ImageView) findViewById(R.id.StartBtnImage);
StartBtnText = (TextView) findViewById(R.id.StartBtnText);
StartBtn.setOnTouchListener(new TouchButton(StartBtnImage)); //Commenting this line makes the onClickListener work
StartBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StartBtnImage.setImageResource(R.drawable.btn_selected);
Log.d("ButtonClick", "Done");
Intent myIntent = new Intent(MainMenu.this, Game.class);
startActivity(myIntent);
}
});
还有我的 TouchButton 类:
public class TouchButton implements View.OnTouchListener {
ImageView IV;
public TouchButton(ImageView Image) {
IV = Image;
}
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
IV.setImageResource(R.drawable.btn_selected);
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_OUTSIDE:
default:
IV.setImageResource(R.drawable.btn);
return false;
}
}
}
这是我的布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainMenu">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/MainMenuBg"
android:background="@drawable/main_menu_bg" />
<RelativeLayout
android:layout_width="250dp"
android:layout_height="75dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="130dp"
android:id="@+id/StartBtn"
android:clickable="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/StartBtnImage"
android:src="@drawable/btn" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Start"
android:id="@+id/StartBtnText"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:singleLine="false"
android:gravity="center|center_vertical|center_horizontal"
android:textSize="50dp" />
</RelativeLayout>
我知道我不擅长解释,所以这里有一个视频:https://www.youtube.com/watch?v=PtdUsW-Dnqk
【问题讨论】:
-
尝试编写自己的按钮选择器(XML 可绘制文件)。
-
我不知道该怎么做。我正在学习教程并按原样做所有事情,但它在我的设备上的工作方式不同。