Search code examples
androidandroid-canvas

How to make EditText clickable?


Sorry if it is sort of duplicate question with this one, I have tried the solutions provided and on some other posts too but none of them are working for me.

I have drawn the EditText but it is not clickable (no keyboard appeared after touch)

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);
}
}

I have also tried this from the solution I saw: (using xml to create the 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>

Change EditText to this and remove canvas.drawBitmap():

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

but the app always force closed when I did this.

Main problem is how to make EditText clickable and show the soft keyboard like when you just put it from xml without drawing it on canvas at all


Solution

  • You can set property of Layout like android:descendantFocusability="beforeDescendants" and 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>
    

    May this one helpful ;)

    How to make EditText not focused when creating Activity