如何使 EditText 可点击?

How to make EditText clickable?

抱歉,如果这是与 this one 的重复问题,我已经尝试了提供的解决方案以及其他一些帖子,但其中 none 对我有用。

我绘制了EditText但是不能点击(触摸后没有出现键盘)

public class GamePanel extends SurfaceView implements SurfaceHolder.Callback{
private LinearLayout lL;
private EditText editText;
@Override
public void surfaceCreated(SurfaceHolder holder){
    lL = new LinearLayout(getContext());

    editText = new EditText(getContext());

    editText.setFocusableInTouchMode(true);
    editText.setClickable(true);
    editText.requestFocus();

    editText.setText("Hello World");
    editText.setVisibility(View.VISIBLE);
    lL.addView(editText);
    lL.setDrawingCacheEnabled(true);
    lL.measure(canvas.getWidth(), canvas.getHeight());
    lL.layout(0, 0, canvas.getWidth(), canvas.getHeight());
    lL.bringChildToFront(editTextView);
}

@Override
public void draw(Canvas canvas){

    canvas.drawBitmap(lL.getDrawingCache(),50,50,null);
}
}

我也从我看到的解决方案中尝试了这个:(使用 xml 创建 EditText)

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

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</RelativeLayout>

将 EditText 更改为此并删除 canvas.drawBitmap():

EditText editText = (EditText)findViewById(R.id.editText1);

但是当我这样做时应用程序总是强制关闭。

主要问题是如何使 EditText 可点击并显示软键盘,就像您刚从 xml 放置它而不在 canvas 上绘制它时那样

您可以设置 属性 的布局,例如 android:descendantFocusability="beforeDescendants"android:focusableInTouchMode="enter code here"

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

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</RelativeLayout>

希望这篇文章对您有所帮助 ;)

How to make EditText not focused when creating Activity

默认情况下,如果您单击 edittext,键盘将可见,除非您做了一些改变行为。无需在 xml 布局中设置可点击、可聚焦。只需创建一个编辑文本并使用它。

如果您想使用编辑文本打开类似 date picker dialog 的内容,您可以使用 set focusable to flase. 因此单击编辑文本将打开对话框等。

示例: android:focusable="flase"