如何使EditText上的父点击?(How to make EditText's paren

2019-09-29 07:30发布

假设我有这样的粉红色框:

它包括LinearLayout与其子: TextView为字段名称和一个EditTextEditText故意禁用。 我想的是,无论用户想上粉红色的框,用户可以点击。 顺便说一句,请忽略任何你发现怪异的UI / UX的事情。

我试过,但用户无法发掘这一地区EditText占据。 用户在挖掘TextView或粉红色框为空区域,这样的应用得到了“点击”。 但是,如果用户点击EditText的面积,什么都不会发生。

我试着在XML属性一些事情,如设置播放LinearLayoutclickabletrue ,和所有的孩子或只是EditText “的的属性clickablefocusable ,并focusableInTouchModefalse ,都无济于事。 EditText面积仍不能点击。

任何想法? 不能只是通过XML来达到? 它应该被编程只是打开旁通做EditText的点击?

Answer 1:

您可以简单地添加onTouch监听器,而不是点击监听器。



Answer 2:

您需要通过的意见,要求父布局(LinearLayout中,不管)和循环,如果你不想将它们绑定所有。 如果您使用数据绑定的容易。 总之,这里是一个解决方案( 需要的代码,一小片!)。

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="out of focus"/>

    <LinearLayout
        android:id="@+id/linearTest"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="test for clicking"
            />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="another clicking test"
            />

        <EditText
            android:id="@+id/editTest"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="focus edittext when clicking linearlayout or other elements inside"
            />
    </LinearLayout>

</LinearLayout>

码:

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.linear_focus_test);

        final EditText editText = (EditText) findViewById(R.id.editTest);

        LinearLayout linearTest = (LinearLayout) findViewById(R.id.linearTest);
            for (int i = 0; i < linearTest.getChildCount(); i++)

            View v = linearTest.getChildAt(i);
            v.setOnClickListener(new View.OnClickListener() {
                @Override public void onClick(View v) {
                    editText.requestFocus();
                }
            });
        }
}

如果你不喜欢的样板,你也可以使用拉姆达(使用1.8功能)

for (int i = 0; i < linearTest.getChildCount(); i++)
            linearTest.getChildAt(i).setOnClickListener(v1 -> editText.requestFocus());

如果您使用至少24 API,你甚至可以把它缩短:

IntStream.range(0, linearTest.getChildCount()).forEach(i -> linearTest.getChildAt(i).setOnClickListener(v1 -> editText.requestFocus()));


文章来源: How to make EditText's parent clickable?