我有一个 android activity xml 和他的 xml 里面 make main RelativeLayout 。那个 RelativeLayout 里面添加一个 Button 和一个 linearlayout 我点击了按钮但没有点击,因为那个按钮过于线性布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btnTest"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:id="@+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</RelativeLayout>
getActivity().findViewById(R.id.btnTest).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick: ");
}
});
点击打印日志。
试试这个:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
<Button
android:id="@+id/btnTest"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Android xml 视图的创建就像一个堆栈,其中 xml 文件中较低的视图呈现在文件中较早的视图之上。
听起来你的线性布局正在拦截触摸事件,阻止它们传播到它下面的按钮。
检查这一点的一种方法是在线性布局上设置背景,您会看到当它具有彩色背景时按钮不可见。
更新:
由于需要允许按钮和布局的触摸事件,我将扩展我的解决方案。
OnClickListeners 是在 android 视图上接收点击事件的标准方法。然而,再往下是OnTouchListeners,它处理视图上的原始触摸而不是点击事件。
当以任何方式触摸安卓屏幕时,事件都会被记录下来,安卓会向触摸事件遇到的第一个视图发送一个触摸事件。 OnTouchListeners 返回一个布尔值,指示他们是否使用了该事件。如果他们没有使用该事件,那么它将传播到触摸事件将遇到的层次结构中的下一个视图。
这就是为什么您的按钮的点击最初从未被注册,因为布局正在消耗触摸事件并阻止它传播到按钮。
这是标准的 android 行为,只有一个视图可以处理任何单个触摸事件。
不这样做的决定表明您应该考虑应用程序的设计并决定是否确实需要这种行为。
但是,如果您的情况是我将提供的罕见情况之一,并以触摸监听器为例。
请注意,这个触摸监听器假设您使用的是我上面发布的 xml 以及他在原始问题中附加到按钮的点击监听器。
getActivity()
.findViewById(R.id.parentLayout)
.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.e(TAG, "onTouch: ");
return false;
}
});
然而,这将在用户触摸布局时触发,并在他们释放时再次触发,因为这是两个独立的运动事件。
要仅触发一种类型的运动事件,您需要检查传递的事件。
getActivity()
.findViewById(R.id.parentLayout)
.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
Log.e(TAG, "onTouch: ");
}
return false;
}
});
在此代码中,日志只会在用户从视图中抬起手指时出现,因为 ACTION_UP 是用户抬起手指的事件操作。
相对布局与线性布局相同,它保留了其中添加的元素的顺序。 您首先添加了按钮,然后添加了线性布局,这就是按钮低于线性布局的原因,因此您无法点击它。 假设按钮视图上方的线性布局,您将看到按钮并通过 java 编码完成剩余部分
将这些行添加到线性布局中:
android:clickable="false"
android:focusableInTouchMode="false"
android:focusable="false"