Android:当EditText是孩子时,如何使布局可点击
我有一个相对布局,里面有一个EditText和一个ImageView。 在某些情况下,我想使整个布局可点击,而不是它的任何子项 我在布局上添加了一个OnClickListener。我对孩子们做了如下尝试: 1.setEnabled(错误) 2.可点击设置(错误) 这适用于ImageView,但即使在上述更改之后,当我单击编辑文本附近的区域时,键盘会弹出,并且我可以在编辑文本中看到光标。 相反,我希望所有点击/触摸事件都能进入布局 有人能帮忙吗?Android:当EditText是孩子时,如何使布局可点击,android,android-layout,android-view,Android,Android Layout,Android View,我有一个相对布局,里面有一个EditText和一个ImageView。 在某些情况下,我想使整个布局可点击,而不是它的任何子项 我在布局上添加了一个OnClickListener。我对孩子们做了如下尝试: 1.setEnabled(错误) 2.可点击设置(错误) 这适用于ImageView,但即使在上述更改之后,当我单击编辑文本附近的区域时,键盘会弹出,并且我可以在编辑文本中看到光标。 相反,我希望所有点击/触摸事件都能进入布局 有人能帮忙吗? 感谢您创建CustomLayout类并重写onIn
感谢您创建CustomLayout类并重写onInterceptTouchEvent方法。如果该方法返回
true
,布局的子对象将不会接收触摸事件。可以创建成员变量和公共setter来更改返回值
自定义布局类
public class CustomLayout extends LinearLayout {
//If set to false, the children are clickable. If set to true, they are not.
private boolean mDisableChildrenTouchEvents;
public CustomLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mDisableChildrenTouchEvents = false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return mDisableChildrenTouchEvents;
}
public void setDisableChildrenTouchEvents(boolean flag) {
mDisableChildrenTouchEvents = flag;
}
}
main活动
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomLayout layout = findViewById(R.id.mylayout);
//Disable touch events in Children
layout.setDisableChildrenTouchEvents(true);
layout.setOnClickListener(v -> System.out.println("Layout clicked"));
}
}
XML布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.dglozano.myapplication.CustomLayout
android:id="@+id/mylayout"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@drawable/outline"
android:clipChildren="true"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter email"
android:inputType="textEmailAddress"
android:layout_gravity="center"/>
</com.example.dglozano.myapplication.CustomLayout>
</android.support.constraint.ConstraintLayout>
请告诉我您是否能让它工作。干杯,是的。谢谢…这是一个聪明的解决方案。