Steven97102
Steven97102

Reputation: 344

How to create a clickable Edittext?

I know a there is a lot of similar questions out there, but none of them work for me. I want to make a EditText that acts like a Button. I want it to be not editable (and no keyboard should popup). However, when I set an onClickListener(), the EditText doesn't react to my onClick() event. How should I do this correctly?

In my xml I disabled the focusableInTouchMode and I set the clickable to be true. My resulting EditText is not editable, but it doesn't response to my onClickListener().

My xml of the EditText:

<EditText
            android:id="@+id/taskviewer_date"
            android:focusableInTouchMode="false"
            android:clickable="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textStyle="normal"
            android:textColorHint="@color/colorShadow"
            android:inputType="none"
            android:hint="No Due Date"/>

My Code:

EditText text = (EditText) findViewById(R.id.taskviewer_date);
text.setOnClickListener(
    new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("taskviewer", "OnClickListener called !");
        }
    }
);

Upvotes: 0

Views: 284

Answers (2)

Srikar Reddy
Srikar Reddy

Reputation: 3708

Use of EditText's setOnClickListener will work if you set setTextIsSelectable to true.

In the XML:

<android.support.design.widget.TextInputLayout 
    android:id="@+id/textInpuLayout" 
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:hint="@string/hint_edit_text" 
    app:layout_constraintEnd_toEndOf="parent" 
    app:layout_constraintStart_toStartOf="parent" 
    app:layout_constraintTop_toTopOf="parent">

<android.support.design.widget.TextInputEditText 
    android:id="@+id/textInpuEditText" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:enabled="false" 
    android:inputType="date"/>
</android.support.design.widget.TextInputLayout>

In the appropriate fragment or the activity:

mTextInpuEditText.setEnabled(true);
mTextInpuEditText.setTextIsSelectable(true);
mTextInpuEditText.setFocusable(false);
mTextInpuEditText.setFocusableInTouchMode(false);
mTextInpuEditText.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Log.d(TAG, "Edit Text is clicked");
    }
});

Upvotes: 1

Hakan Saglam
Hakan Saglam

Reputation: 211

Use onTouch events or put a clickable FrameLayout over your EditText to catch click events. Make FrameLayout's visibility Gone when you want your edittext to be editable

Upvotes: 2

Related Questions