最後にcross(x)ボタンを含むEditTextを作成する方法は?


198

EditTextクロスボタンを含むようなウィジェットはありますか、それともEditText自動的に作成されるプロパティはありますか?十字ボタンで、で書かれたテキストを削除したいEditText


2
そのための標準的なウィジェットではないようです。しかし、「android edittext clear button x」をGoogle検索すると、いくつかの異なるアプローチが見つかります。だから「クリアボタン」が彼らの呼んでいるものだと思います。また、関連する質問にこの答えを参照してください。stackoverflow.com/questions/4175398/clear-edittext-on-click/...
HostileForkがdont信頼SE語る

あなたはここにソースをダウンロードすることができます:github.com/GhOsTTT/editTextXbuttonは良い一日を
グーカンMusapaşaoğluヅ

本質的に重複している別の質問は、Androidにuitextfieldプロパティを実装
Alex Cohn

回答:


166

次のレイアウトを使用します。

<FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="9dp"
    android:padding="5dp">

    <EditText
        android:id="@+id/calc_txt_Prise"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"  
        android:layout_marginTop="20dp"
        android:textSize="25dp"
        android:textColor="@color/gray"
        android:textStyle="bold"
        android:hint="@string/calc_txt_Prise"
        android:singleLine="true" />

    <Button
        android:id="@+id/calc_clear_txt_Prise"      
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:layout_gravity="right|center_vertical"
        android:background="@drawable/delete" />

</FrameLayout>

ボタンのIDを使用して、そのonClickListenerメソッドで必要なアクションを実行することもできます。


8
これは、非効率的な方法です。ヤンチェンコの答えは、複合ドローアブルを使用する正しいアプローチです。
numan salati 2013

4
このソリューションを選択して、画像が大きく引き伸ばされていることに気付いた場合は、通常のボタンの代わりにImageButtonを使用する必要があります。
personne3000

3
このソリューションは「非効率的」ですが、視覚障害者にとってははるかにアクセスしやすいものです。ドローアブルを使用すると、ユーザーはテキストをクリアするために非常に複雑な操作を実行する必要があります。これは、ユーザーがXボタンを使用してすばやく実行できる操作です。
Daniel Monteiro

2
これの非効率性は何ですか?
デニー

121

あなたがたまたまDroidPartsを使用しているのであれば、私はClearableEditTextを追加しました

カスタム背景とクリアアイコンabs__ic_clear_holo_lightActionBarSherlockから設定すると、次のようになります

ここに画像の説明を入力してください


11
クラスが拡張されるため、最適なソリューションですEditText。@yanchenko THX
tbruyelle

2
@stephanek。これを開発ブランチで修正しました。1.4.3リリースの一部になります。
yanchenko 2013

4
ありがとう!ClearableAutoCompleteTextViewをDroidPartsに含めることもできれば、本当にすばらしいでしょう。これを実行しようとする他のユーザーの場合:DroidPartsライブラリを使用して、ClearableEditTextからコードをコピーし、AutoCompleteTextViewを拡張します。
RobinDeCroon 2014

2
これは爆弾です!スタンドアロンで使用して、通常のTextWatcherでTextWatcherAdapter依存関係を変更することもできます。
Pimentoso 14

1
@yanchenko実装を確認しました。許容されるタッチ領域がかなり小さいことと、編集テキスト内のy軸に沿ってすべてのタッチイベントを受け入れるデフォルトの高さよりも大きい編集テキストを使用することの間には、多少のトレードオフがあるようです。あなたの実装は前者であり、後者は私のものです。同様の状況で、同じことを行うことをお勧めしますか?つまり、誤って押されたり、ヒットボックスが大きくなったりする小さなヒットボックスを使用します。拡張または大きな編集テキストを使用すると、プレスはドローアブルの境界の外に出る可能性があります。
Jack.Ramsden 2016年

64

Android向けマテリアルデザインコンポーネントによる2020ソリューション:

GradleセットアップにMaterial Componentsを追加します。

こちらから最新バージョンを探してください:https : //maven.google.com/

implementation 'com.google.android.material:material:1.1.0'

または、AndroidXライブラリを使用するように更新していない場合は、次の方法で追加できます。

implementation 'com.android.support:design:28.0.0'

その後

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/hint_text"
    app:endIconMode="clear_text">

  <com.google.android.material.textfield.TextInputEditText
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>

</com.google.android.material.textfield.TextInputLayout>

注意:app:endIconMode = "clear_text"

ここで説明したように、マテリアルデザインのドキュメント


10
これは、新しく受け入れられた答えになるはずです。私の場合、AndroidXライブラリを更新せずに実装することはできませんでした。
ベン

@ベン(
グッド

すべてのxml属性がまだサポートされているわけではないため、必ずドキュメントをお読みください。正確な実装の詳細がある場合があるため、ソースメッセージまたはコミットメッセージを確認する必要がある場合があります。カスタムendIconでこの種の問題が発生しました。コミットメッセージにより、xml属性にはまだそれをサポートする実装がないことが明らかになりました。実装が完了するまで別のアプローチを使用する必要がある
M. Smith

2020年のベストの答え
サム・チェン

app:endIconMode = "clear_text"はどのように機能し<androidx.appcompat.widget.AppCompatEditText/>ますか?あなたは同じで私を助けてくださいすることができます
Arbaz.in

32

これはkotlinソリューションです。このヘルパーメソッドをいくつかのkotlinファイルに入れます。

fun EditText.setupClearButtonWithAction() {

    addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(editable: Editable?) {
            val clearIcon = if (editable?.isNotEmpty() == true) R.drawable.ic_clear else 0
            setCompoundDrawablesWithIntrinsicBounds(0, 0, clearIcon, 0)
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
    })

    setOnTouchListener(View.OnTouchListener { _, event ->
        if (event.action == MotionEvent.ACTION_UP) {
            if (event.rawX >= (this.right - this.compoundPaddingRight)) {
                this.setText("")
                return@OnTouchListener true
            }
        }
        return@OnTouchListener false
    })
}

そして、onCreateメソッドで次のように使用します。

yourEditText.setupClearButtonWithAction()

ところで、あなたはR.drawable.ic_clear最初に、またはクリアアイコンを追加する必要があります。これはgoogle- https://material.io/tools/icons/?icon=clear&style=baselineからのものです


this.clearFocus()return trueステートメントの前に挿入すると、onFocusChangeリスナーを使用してEditText呼び出し元でこのイベントをリッスンできます
Joost Schepel

すばらしい、問題です。AppCompatEditTextで描画可能な左のアイコンを設定するだけです。この関数を呼び出すと削除されます。問題を教えてください。
Arbaz.in

@ Arbaz.inメソッドの呼び出しが原因ですsetCompoundDrawablesWithIntrinsicBounds(0, 0, clearIcon, 0)。左側のドローアブルアイコンIDを新しいパラメータとしてこの関数に渡し、それを呼び出しに入れることができます。
グルシャン

@Gulshan私は同じことをしましたが、そのドローアブルを削除します
Arbaz.in

20

Androidのサポートライブラリには、SearchViewまさにこれを行うクラスがあります。(EditTextただし、派生ではないので、のSearchView.OnQueryTextListener代わりにを使用する必要がありますTextWatcher

テキストなしの検索ビュー(およびヒントテキスト「検索」)

ここに画像の説明を入力してください

次のようにXMLで使用します。

  <android.support.v7.widget.SearchView
            android:id="@+id/searchView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:iconifiedByDefault="false"
            android:queryHint="@string/SearchHint"
            app:iconifiedByDefault="false"
            app:queryHint="@string/SearchHint" />

16
Drawable x = getResources().getDrawable(R.drawable.x);
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
mEditText.setCompoundDrawables(null, null, x, null);

ここで、xは次のとおりです。

ここに画像の説明を入力してください


8
それでもonClickListenerを割り当てる必要がありますか?クイック検索は私にこれを与えまし。より良い解決策は、Framelayoutを使用することです。ありがとうございます!
VenoM 2013年


6

カスタムビューや特別なレイアウトを使用したくない場合は、9パッチを使用して(X)ボタンを作成できます。

例:http : //postimg.org/image/tssjmt97p/(StackOverflowに画像を投稿するための十分なポイントがない)

右と下の黒いピクセルの交点がコンテンツ領域を表します。その領域の外側はパディングです。したがって、ユーザーがxをクリックしたことを検出するには、次のようにOnTouchListenerを設定できます。

editText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP){
                    if (motionEvent.getX()>(view.getWidth()-view.getPaddingRight())){
                        ((EditText)view).setText("");
                    }
                }
                return false;
            }
        });

必要に応じて、このソリューションはいくつかのケースでうまく機能します。私は自分のxmlをそれほど複雑にしないことを好みます。これは、アイコンを9パッチに含めるだけでよいので、アイコンを左側に配置したい場合にも役立ちます。


4

私は以下のようにUI部分を行いました:

<RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:layout_marginTop="9dp"
            android:padding="5dp">

            <EditText
                android:id="@+id/etSearchToolbar"
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:textSize="13dp"
                android:padding="10dp"
                android:textColor="@android:color/darker_gray"
                android:textStyle="normal"
                android:hint="Search"
                android:imeOptions="actionSearch"
                android:inputType="text"
                android:background="@drawable/edittext_bg"
                android:maxLines="1" />

            <ImageView
                android:id="@+id/ivClearSearchText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginRight="6dp"
                android:src="@drawable/balloon_overlay_close"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true" />


        </RelativeLayout>

edittext_bg.xml

<?xml version="1.0" encoding="utf-8"?>

<solid android:color="#FFFFFF" />

<stroke
    android:width="1dp"
    android:color="#C9C9CE" />

<corners
    android:bottomLeftRadius="15dp"
    android:bottomRightRadius="15dp"
    android:topLeftRadius="15dp"
    android:topRightRadius="15dp" />

balloon_overlay_close.pngここに画像の説明を入力してください

クロス/クリアボタンの非表示/表示:

searchBox.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            if(charSequence.length() > 0){
                clearSearch.setVisibility(View.VISIBLE);
            }else{
                clearSearch.setVisibility(View.GONE);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {}
    });

検索項目の処理(つまり、ユーザーがソフトキーボードから検索をクリックしたとき)

searchBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String contents = searchBox.getText().toString().trim();
                if(contents.length() > 0){
                    //do search

                }else
                    //if something to do for empty edittext

                return true;
            }
            return false;
        }
    });`

クリア/クロスボタン

  clearSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            searchBox.setText("");
        }
    });


2

これがウィジェットを含む完全なライブラリです:https : //github.com/opprime/EditTextField

これを使用するには、依存関係を追加する必要があります。

compile 'com.optimus:editTextField:0.2.0'

layout.xmlファイルでは、ウィジェット設定で遊ぶことができます。

xmlns:app="http://schemas.android.com/apk/res-auto"
  • app:clearButtonMode、can can such such values:never while whileEditing without Editing

  • app:clearButtonDrawable

実際のサンプル:

ここに画像の説明を入力してください


2

ちょうどdrawableEndあなたのように近いクロスを入れてくださいEditText

<EditText
     ...
    android:drawableEnd="@drawable/ic_close"
    android:drawablePadding="8dp"
     ... />

拡張機能使用してクリックを処理します(またはでOnTouchListener直接使用しますEditText):

fun EditText.onDrawableEndClick(action: () -> Unit) {
    setOnTouchListener { v, event ->
        if (event.action == MotionEvent.ACTION_UP) {
            v as EditText
            val end = if (v.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL)
                v.left else v.right
            if (event.rawX >= (end - v.compoundPaddingEnd)) {
                action.invoke()
                return@setOnTouchListener true
            }
        }
        return@setOnTouchListener false
    }
}

拡張機能の使用:

editText.onDrawableEndClick {
    // TODO clear action
    etSearch.setText("")
}

1

このスニペットを複数のボタンに対してJaydip回答とともに使用できます。ET要素とボタン要素への参照を取得した後で呼び出すだけです。vecotrボタンを使用したので、Button要素をImageButtonに変更する必要があります。

private void setRemovableET(final EditText et, final ImageButton resetIB) {

        et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus && et.getText().toString().length() > 0)
                    resetIB.setVisibility(View.VISIBLE);
                else
                    resetIB.setVisibility(View.INVISIBLE);
            }
        });

        resetIB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et.setText("");
                resetIB.setVisibility(View.INVISIBLE);
            }
        });

        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {}
            @Override
            public void beforeTextChanged(CharSequence s, int start,
                                          int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start,
                                      int before, int count) {
                if(s.length() != 0){
                    resetIB.setVisibility(View.VISIBLE);
                }else{
                    resetIB.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

0

フレームレイアウトを使用している場合、またはフレームレイアウトを作成できる場合は、別の方法を試しました。

<TextView
    android:id="@+id/inputSearch"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawableRight="@drawable/ic_actionbar"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/back_button"/>

<Button
    android:id="@+id/clear_text_invisible_button"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_gravity="right|center_vertical"
    android:background="@color/transparent"
    android:layout_alignBaseline="@+id/inputSearch"
    android:layout_alignBottom="@+id/inputSearch"
    android:layout_alignRight="@+id/inputSearch"
    android:layout_alignEnd="@+id/inputSearch"
    android:layout_marginRight="13dp"
    />

これは、クロスドローを右のドローアブルとして配置したエディットテキストです。UPONよりも、テキストをクリアする透明なボタンを配置しています。


0
    <EditText
    android:id="@+id/idSearchEditText"
    android:layout_width="match_parent"
    android:layout_height="@dimen/dimen_40dp"
    android:drawableStart="@android:drawable/ic_menu_search"
    android:drawablePadding="8dp"
    android:ellipsize="start"
    android:gravity="center_vertical"
    android:hint="Search"
    android:imeOptions="actionSearch"
    android:inputType="text"
    android:paddingStart="16dp"
    android:paddingEnd="8dp"
/>

EditText mSearchEditText = findViewById(R.id.idSearchEditText);
mSearchEditText.addTextChangedListener(this);
mSearchEditText.setOnTouchListener(this);


@Override
public void afterTextChanged(Editable aEditable) {
    int clearIcon = android.R.drawable.ic_notification_clear_all;
    int searchIcon = android.R.drawable.ic_menu_search;
    if (aEditable == null || TextUtils.isEmpty(aEditable.toString())) {
        clearIcon = 0;
        searchIcon = android.R.drawable.ic_menu_search;
    } else {
        clearIcon = android.R.drawable.ic_notification_clear_all;
        searchIcon = 0;
    }
    Drawable leftDrawable =  null;
    if (searchIcon != 0) {
        leftDrawable = getResources().getDrawable(searchIcon);
    }
    Drawable rightDrawable = null;
    if (clearIcon != 0) {
        rightDrawable = getResources().getDrawable(clearIcon);
    }

    mSearchEditText.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, null, rightDrawable, null);
}


@Override
public boolean onTouch(View aView, MotionEvent aEvent) {
    if (aEvent.getAction() == MotionEvent.ACTION_UP){
        if (aEvent.getX() > ( mSearchEditText.getWidth() - 
         mSearchEditText.getCompoundPaddingEnd())){
            mSearchEditText.setText("");
        }
    }
    return false;
}
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.