【问题标题】:How to make Layout clickable which has disabled EditText and Button如何使禁用 EditText 和 Button 的布局可点击
【发布时间】:2019-03-28 21:01:39
【问题描述】:

我有一个简单的布局,带有 EditText 和一个按钮。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:clickable="true"
    android:focusable="true">

    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:focusable="false"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"/>

</LinearLayout>

我不希望 EdiText 是可编辑的并且想要处理点击完整布局

 public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.linearLayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

但它不起作用我的意思是当我点击时没有 Toast 消息。

【问题讨论】:

  • 什么“不工作”?
  • 点击时没有Toast消息。
  • 发布更多您的课程。你在夸大这个布局吗?
  • 你是点击按钮还是布局?
  • 您可以在按钮android:clickable="false"上再添加一个属性并查看结果

标签: android


【解决方案1】:

正如@Liem Vo 在 cmets 中所说:您应该将android:clickable="false" 添加到按钮中,并确保不要在 java 中添加单击侦听器。 因为事件是由子视图处理的。

对于“EditText”,您可以手动调用父母点击监听器:

editText.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            View parent = (View) v.getParent();
            parent.performClick();
        }
    });

请参考这个问题:onClick not triggered on LinearLayout with child

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多