即使EditText不可编辑,EditText游标也是可见的 [英] EditText cursor visible even if the EditText is not editable

查看:197
本文介绍了即使EditText不可编辑,EditText游标也是可见的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 EditText 中引入数据,但是我想使用虚拟键盘,而不是android键盘。如果我使用 setKeyListener(null),那么即使在使用 setCursorVisible(true)

之后,光标也是不可见的b
$ b

是否可以创建一个 EditText ,即使它不可编辑,游标是可见的? b

编辑2:
我发现了一个部分的方法来做到这一点,但是当我双击EditText的时候它不工作。
$ b

我为 setOnClickListner()和一个 setOnLongClickListner() code>的EditText 。在这种方法中,我隐藏窗口的软输入,也使用 setTextIsSelectable(false)。我唯一的问题是,当我双击 EditText 软输入键盘显示,我不知道如何隐藏它,我试图使用 android:清单中的windowSoftInputMode =stateAlwaysHidden,但它也不起作用。

编辑:



下面是我现在使用的代码,用于我的基本转换器计算器。

  public class MainActivity extends AppCompatActivity {

EditText number;
EditText base;
boolean baseB = false;
String numberS =0;
String baseS =10;

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


//使EditText为数字和base不可编辑
number =(EditText)findViewById(R.id.number);
number.setKeyListener(null);
ase =(EditText)findViewById(R.id.base);
base.setKeyListener(null);

// ...更多的代码在这里(改变每个EditText的字体和改变状态栏的颜色



//我有一个函数每个按钮都是相同的

public void onClickBaseChange(View v){
if(baseB){
baseB = false;
//我使用toasts这一刻知道当我在数字或基地领域
Toast.makeText(这,数字,Toast.LENGTH_SHORT).show();
)其他{
baseB = true ;
Toast.makeText(this,Base,Toast.LENGTH_SHORT).show();
}
}

public void onClickB0(View v){
if(numberS.length()> 0&!numberS.equals(0)&!baseB){
numberS + =0;
number =(EditText)findViewById(R.id.number);
number.setText(numberS,TextView.BufferType.EDITABLE);
number.setSelection(numberS.length());
} else {
if(Integer.valueOf(baseS)> = 1){
b aseS + =0;
ase =(EditText)findViewById(R.id.base);
base.setText(baseS,TextView.BufferType.EDITABLE);



$ public void onClickB1(View v){
if(numberS.equals(0)){
numberS =1;
} else {
numberS + =1;
}
number =(EditText)findViewById(R.id.number);
number.setText(numberS,TextView.BufferType.EDITABLE);
number.requestFocus();
number.setSelection(numberS.length());

$ / code>

xml看起来像这样:

 < android.widget.RelativeLayout xmlns:android =http://schemas.android.com/apk/res/android
xmlns:app =http://schemas.android.com/apk/res-auto
xmlns:tools =http://schemas.android.com/tools
android:layout_width =fill_parent
android:layout_height =fill_parent
android:background =@ color / colorBackground

tools:context =manastur.calculator.MainActivity>

$ b< EditText
android:id =@ + id / base
android:layout_width =wrap_content
android:layout_height = wrap_content
android:layout_alignParentRight =true
android:layout_marginRight =20dp
android:layout_marginTop =120dp
android:background =@ android:color / transparent
android:cursorVisible =true
android:text =
android:textColor =@ color / text
android:textSize =30dp/>

编辑文本
android:id =@ + id / number
android:layout_width =wrap_content
android:layout_height =wrap_content
android:layout_alignParentTop =true
android:layout_marginLeft =30dp
android:layout_marginTop =50dp
android:background =@ android:color / transparent
android:cursorVisible =true
android:text =
android:textColor =@ color / text
android:textSize =50dp/>

$ b< LinearLayout
android:id =@ + id / secondRow
android:layout_width =wrap_content
android:layout_height = wrap_content
android:layout_above =@ + id / firstRow
android:layout_centerHorizo​​ntal =true>


解决方案



开发时,我从原生 Dialpad code



KeypadlessKeypad.java

  import android.content.Context; 
导入android.graphics.Rect;
导入android.support.v4.view.MotionEventCompat;
导入android.text.InputType;
导入android.util.AttributeSet;
导入android.view.MotionEvent;
导入android.view.View;
导入android.view.accessibility.AccessibilityEvent;
导入android.view.inputmethod.InputMethodManager;
导入android.widget.EditText;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class KeypadlessKeypad extends EditText {

private static final方法mShowSoftInputOnFocus = getSetShowSoftInputOnFocusMethod(
EditText.class,setShowSoftInputOnFocus,boolean.class);
$ b public static Method getSetShowSoftInputOnFocusMethod(Class<?> cls,String methodName,Class<> ... parametersType){
Class<?> sCls = cls.getSuperclass();
while(sCls!= Object.class){
try {
return sCls.getDeclaredMethod(methodName,parametersType);
catch(NoSuchMethodException e){
//再超级
}
sCls = sCls.getSuperclass();
}
返回null;
}

private Context mContext;

$ b / **
*用于复制,剪切和粘贴事件的监听器
*目前只对Paste事件执行回调
* /
private OnEditTextActionListener mOnEditTextActionListener;

public KeypadlessKeypad(Context context){
super(context);
mContext = context;
init();


public KeypadlessKeypad(Context context,AttributeSet attrs){
super(context,attrs);
mContext = context;
init();

$ b $ public KeypadlessKeypad(Context context,AttributeSet attrs,
int defStyle){
super(context,attrs,defStyle);
mContext = context;

init();

$ b $覆盖$ b $保护void onSelectionChanged(int selStart,int selEnd){
super.onSelectionChanged(selStart,selEnd);


$ b public final void appendText(CharSequence text){
append(text,0,text.length());
}

/ ***
*初始化TextView的所有必需组件。
* /
private void init(){

setSingleLine(true);

synchronized(this){
setInputType(getInputType()| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
setFocusableInTouchMode(true);
}

reflexSetShowSoftInputOnFocus(false); //解决方法

//确保初始化光标在输入框的末尾。如果没有这个,当通过布局XML添加文本时,
//光标可能在索引0处。
setSelection(getText()。length());

$ b @Override
protected void onFocusChanged(boolean focused,int direction,Rect previouslyFocusedRect){
super.onFocusChanged(focused,direction,previouslyFocusedRect);
hideKeyboard();


@Override
public boolean onTouchEvent(MotionEvent event){
final boolean ret = super.onTouchEvent(event);
//必须在super.onTouchEvent()之后完成
hideKeyboard();
return ret;

$ b private void hideKeyboard(){
final InputMethodManager imm =((InputMethodManager)getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE));
if(imm!= null& imm.isActive(this)){
imm.hideSoftInputFromWindow(getApplicationWindowToken(),0);


$ b private void refSsetShowSoftInputOnFocus(boolean show){
if(mShowSoftInputOnFocus!= null){
invokeMethod(mShowSoftInputOnFocus,this,show) ;
} else {
//使用后备方法。没有测试。
hideKeyboard();



public static Object invokeMethod(Method method,Object receiver,Object ... args){
try {
return method.invoke (接收者,参数); catch(IllegalAccessException e){
} catch(InvocationTargetException e){
}

catch

$ b @Override
protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec){
super.onMeasure(widthMeasureSpec,heightMeasureSpec);

textViewWidth = View.MeasureSpec.getSize(widthMeasureSpec);
int height = getMeasuredHeight();

this.setMeasuredDimension(textViewWidth,height);

$ b @Override
protected void onTextChanged(CharSequence text,int start,int before,
int after){
super.onTextChanged(text,开始,之前,之后);

$ b $ @覆盖
保护无效onSizeChanged(int w,int h,int oldw,int oldh){
}

@覆盖
public boolean onTextContextMenuItem(int id){
boolean consume = super.onTextContextMenuItem(id);

switch(id){
case android.R.id.paste:
if(mOnEditTextActionListener!= null){
mOnEditTextActionListener.onPaste();
}
break;
}

消耗的回报;


$ b / **
* {@link #mOnEditTextActionListener}的设置方法
*
* @param onEditTextActionListener
* OnEditTextActionListener的实例
* /
public void setOnEditTextActionListener(OnEditTextActionListener onEditTextActionListener){
this.mOnEditTextActionListener = onEditTextActionListener;
}


private Rect mRect = new Rect();
$ b $ @覆盖
public boolean dispatchTouchEvent(MotionEvent event){
final int action = MotionEventCompat.getActionMasked(event);

int [] location = new int [2];
getLocationOnScreen(location);
mRect.left = location [0];
mRect.top = location [1];
mRect.right = location [0] + getWidth();
mRect.bottom = location [1] + getHeight();

int x =(int)event.getX();
int y =(int)event.getY();

if(action == MotionEvent.ACTION_DOWN&&!mRect.contains(x,y)){
InputMethodManager input =(InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(getWindowToken(),0);
}
返回super.dispatchTouchEvent(event);

$ b @Override
public void sendAccessibilityEventUnchecked(AccessibilityEvent event){
if(event.getEventType()== AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED){
/ /由于我们每次添加或删除
//字符都要替换文本,只能读取其中的差异。 (issue 5337550)
final int added = event.getAddedCount();
final int removed = event.getRemovedCount();
final int length = event.getBeforeText()。length();
if(添加&删除){
event.setRemovedCount(0);
event.setAddedCount(1);
event.setFromIndex(length);
} else if(removed> added){
event.setRemovedCount(1);
event.setAddedCount(0);
event.setFromIndex(length - 1);
} else {
return;
}
} else if(event.getEventType()== AccessibilityEvent.TYPE_VIEW_FOCUSED){
//父EditText类让tts读取编辑框,当这个View有一个焦点时,
//让用户在应用程序启动时感到困惑(问题5275935)。
return;
}
super.sendAccessibilityEventUnchecked(event);

$ b / **
*从Edittext复制,剪切和粘贴事件获取回调的接口
*仅仅是生成粘贴事件回调
* /
public interface OnEditTextActionListener {
$ b $ / **
*如果Edittext获取粘贴事件,则此方法将被称为
* /
void onPaste();





在你的xml中,这个,

 < [package name] .KeypadlessKeypad 
android:id =@ + id / dialnumbertv
android:layout_width =match_parent
android:layout_height =wrap_content
android:background =#00000000
android:cursorVisible =false
android: ellipsize =start
android:gravity =center
android:inputType =phone
android:singleLine =true
android:textIsSelectable =true
android:textSize =30sp
android:textStyle =italic
android:visibility =visible/>

在你的片段中你可以像这样实现,

pre> public void onViewCreated(final View view,Bundle savedInstanceState){
super.onViewCreated(view,savedInstanceState);

mDialNumbertv = view.findViewById(R.id.dialnumbertv);

mDialNumbertv.setCursorVisible(false);

mDialNumbertv.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(!isDigitsEmpty()){
mDialNumbertv.setCursorVisible(true);
}
}
});

mDialNumbertv.addTextChangedListener(new TextWatcher(){
@Override
public void beforeTextChanged(CharSequence s,int start,int count,int after){


$ b @Override
public void onTextChanged(CharSequence s,int start,int before,int count){

}

@Override
public void afterTextChanged(editable s){
if(isDigitsEmpty()){
mDialNumbertv.setCursorVisible(false);
}
// updateDeleteButton );
}
});

mDialNumbertv.setOnLongClickListener(new View.OnLongClickListener(){
@Override
public boolean onLongClick(View v){
// Ref https:// android。 googlesource.com/platform/packages/apps/Contacts/+/39948dc7e34dc2041b801058dada28fedb80c388/src/com/android/contacts/dialpad/DialpadFragment.java
//现在EditText在光标不显示时显示粘贴选项可见的
//为了显示,使光标可见,并返回false,让EditText
//显示自己的选项
mDialNumbertv.setCursorVisible(true);
返回false;
}
});

mDialNumbertv.setOnEditTextActionListener(
new KeypadlessKeypad.OnEditTextActionListener(){
@Override
public void onPaste(){
//如果粘贴了某些内容mDialNumbertv
//我们需要在联系人和价格上运行一些搜索
$ b $ String mobileNumber = mDialNumbertv.getText()。toString();

if(TextUtils。 isEmpty(mobileNumber)){
return;
}

// updateContactName(mobileNumber);
}
});

}

private KeypadlessKeypad mDialNumbertv;

private boolean isDigitsEmpty(){
return mDialNumbertv.length()== 0;

$ b $ private void setClickedDigit(final String digitToSet){
if(!TextUtils.isEmpty(digitToSet)){

char digit = digitToSet。的charAt(0);

字符串mobileNumber = mDialNumbertv.getText()+ digitToSet;
mDialNumbertv.getText()。insert(mDialNumbertv.getSelectionStart(),digitToSet);

//如果光标位于文本的末尾,我们将其隐藏。
final int length = mDialNumbertv.length();
if(length == mDialNumbertv.getSelectionStart()&&& length == mDialNumbertv.getSelectionEnd()){
mDialNumbertv.setCursorVisible(false);
}
}
}


I need to introduce data in an EditText but i want to use an virtual keyboard, not the android keyboard. If I use setKeyListener(null) the cursor is invisible even after using setCursorVisible(true).

Is it possible to make an EditText where even if it isn't editable the cursor is visible ?

EDIT 2 : I found an partial method to do that, but it's not working when i'm double taping the EditText.

I made an setOnClickListner() and an setOnLongClickListner() method for the EditText. In this methods I hide the Soft Input from the Window, also i use setTextIsSelectable(false). My only problem is that when I double tap the EditText the soft input keyboard shows and I dont know how to hide it, I tried to use android:windowSoftInputMode="stateAlwaysHidden" in manifest, but it doesn't work either.

EDIT :

Here is the code that I'm using at this moment for my base converter calculator.

public class MainActivity extends AppCompatActivity {

EditText number;
EditText base;
boolean baseB = false;
String numberS = "0";
String baseS = "10";

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


    //make the EditText for number and base not editable
    number = (EditText) findViewById(R.id.number);
    number.setKeyListener(null);
    base = (EditText) findViewById(R.id.base);
    base.setKeyListener(null);

    //... more code here (changing fonts for each EditText and changing status bar color

}

// I have a function for each button all are the same

public void onClickBaseChange(View v) {
    if (baseB) {
        baseB = false;
        // i use toasts at this moment to know when i'm on number or base field
        Toast.makeText(this, "Number", Toast.LENGTH_SHORT).show();
    } else {
        baseB = true;
        Toast.makeText(this, "Base", Toast.LENGTH_SHORT).show();
    }
}

public void onClickB0(View v) {
    if (numberS.length() > 0 && !numberS.equals("0") && !baseB) {
        numberS += "0";
        number = (EditText) findViewById(R.id.number);
        number.setText(numberS, TextView.BufferType.EDITABLE);
        number.setSelection(numberS.length());
    } else {
        if (Integer.valueOf(baseS) >= 1) {
            baseS += "0";
            base = (EditText) findViewById(R.id.base);
            base.setText(baseS, TextView.BufferType.EDITABLE);
        }
    }
}

public void onClickB1(View v) {
    if (numberS.equals("0")) {
        numberS = "1";
    } else {
        numberS += "1";
    }
    number = (EditText) findViewById(R.id.number);
    number.setText(numberS, TextView.BufferType.EDITABLE);
    number.requestFocus();
    number.setSelection(numberS.length());
}

And the xml looks like this :

<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/colorBackground"

tools:context="manastur.calculator.MainActivity">


<EditText
    android:id="@+id/base"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_marginRight="20dp"
    android:layout_marginTop="120dp"
    android:background="@android:color/transparent"
    android:cursorVisible="true"
    android:text=""
    android:textColor="@color/text"
    android:textSize="30dp" />

<EditText
    android:id="@+id/number"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="30dp"
    android:layout_marginTop="50dp"
    android:background="@android:color/transparent"
    android:cursorVisible="true"
    android:text=""
    android:textColor="@color/text"
    android:textSize="50dp" />


<LinearLayout
    android:id="@+id/secondRow"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/firstRow"
    android:layout_centerHorizontal="true">

    <Button
        android:id="@+id/b1"
        android:layout_width="85dp"
        android:layout_height="85dp"
        android:background="@drawable/b1"
        android:onClick="onClickB1" />

    <Button
        android:id="@+id/b2"
        android:layout_width="85dp"
        android:layout_height="85dp"
        android:background="@drawable/b2"
        android:onClick="onClickB2" />

   <!-- from this point on is the same, there are 5 LinearLayouts which
   represents the 5 rows of button of the num pad -->       

解决方案

Use this code to achieve that,

While develop I took reference from native Dialpad code

KeypadlessKeypad.java

import android.content.Context;
import android.graphics.Rect;
import android.support.v4.view.MotionEventCompat;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class KeypadlessKeypad extends EditText {

    private static final Method mShowSoftInputOnFocus = getSetShowSoftInputOnFocusMethod(
            EditText.class, "setShowSoftInputOnFocus", boolean.class);

    public static Method getSetShowSoftInputOnFocusMethod(Class<?> cls, String methodName, Class<?>... parametersType) {
        Class<?> sCls = cls.getSuperclass();
        while (sCls != Object.class) {
            try {
                return sCls.getDeclaredMethod(methodName, parametersType);
            } catch (NoSuchMethodException e) {
                // Just super it again
            }
            sCls = sCls.getSuperclass();
        }
        return null;
    }

    private Context mContext;


    /**
     * Listener for Copy, Cut and Paste event
     * Currently callback only for Paste event is implemented
     */
    private OnEditTextActionListener mOnEditTextActionListener;

    public KeypadlessKeypad(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public KeypadlessKeypad(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }

    public KeypadlessKeypad(Context context, AttributeSet attrs,
                            int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;

        init();
    }

    @Override
    protected void onSelectionChanged(int selStart, int selEnd) {
        super.onSelectionChanged(selStart, selEnd);
    }


    public final void appendText(CharSequence text) {
        append(text, 0, text.length());
    }

    /***
     * Initialize all the necessary components of TextView.
     */
    private void init() {

        setSingleLine(true);

        synchronized (this) {
            setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
            setFocusableInTouchMode(true);
        }

        reflexSetShowSoftInputOnFocus(false); // Workaround.

        // Ensure that cursor is at the end of the input box when initialized. Without this, the
        // cursor may be at index 0 when there is text added via layout XML.
        setSelection(getText().length());
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        hideKeyboard();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        final boolean ret = super.onTouchEvent(event);
        // Must be done after super.onTouchEvent()
        hideKeyboard();
        return ret;
    }

    private void hideKeyboard() {
        final InputMethodManager imm = ((InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE));
        if (imm != null && imm.isActive(this)) {
            imm.hideSoftInputFromWindow(getApplicationWindowToken(), 0);
        }
    }

    private void reflexSetShowSoftInputOnFocus(boolean show) {
        if (mShowSoftInputOnFocus != null) {
            invokeMethod(mShowSoftInputOnFocus, this, show);
        } else {
            // Use fallback method. Not tested.
            hideKeyboard();
        }
    }

    public static Object invokeMethod(Method method, Object receiver, Object... args) {
        try {
            return method.invoke(receiver, args);
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {
        }

        return null;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int textViewWidth = View.MeasureSpec.getSize(widthMeasureSpec);
        int height = getMeasuredHeight();

        this.setMeasuredDimension(textViewWidth, height);
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int before,
                                 int after) {
        super.onTextChanged(text, start, before, after);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    }

    @Override
    public boolean onTextContextMenuItem(int id) {
        boolean consumed = super.onTextContextMenuItem(id);

        switch (id) {
            case android.R.id.paste:
                if (mOnEditTextActionListener != null) {
                    mOnEditTextActionListener.onPaste();
                }
                break;
        }

        return consumed;
    }


    /**
     * Setter method for {@link #mOnEditTextActionListener}
     *
     * @param onEditTextActionListener
     *         Instance of the {@link OnEditTextActionListener}
     */
    public void setOnEditTextActionListener(OnEditTextActionListener onEditTextActionListener) {
        this.mOnEditTextActionListener = onEditTextActionListener;
    }


    private Rect mRect = new Rect();

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        final int action = MotionEventCompat.getActionMasked(event);

        int[] location = new int[2];
        getLocationOnScreen(location);
        mRect.left = location[0];
        mRect.top = location[1];
        mRect.right = location[0] + getWidth();
        mRect.bottom = location[1] + getHeight();

        int x = (int) event.getX();
        int y = (int) event.getY();

        if (action == MotionEvent.ACTION_DOWN && !mRect.contains(x, y)) {
            InputMethodManager input = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            input.hideSoftInputFromWindow(getWindowToken(), 0);
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED) {
            // Since we're replacing the text every time we add or remove a
            // character, only read the difference. (issue 5337550)
            final int added = event.getAddedCount();
            final int removed = event.getRemovedCount();
            final int length = event.getBeforeText().length();
            if (added > removed) {
                event.setRemovedCount(0);
                event.setAddedCount(1);
                event.setFromIndex(length);
            } else if (removed > added) {
                event.setRemovedCount(1);
                event.setAddedCount(0);
                event.setFromIndex(length - 1);
            } else {
                return;
            }
        } else if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED) {
            // The parent EditText class lets tts read "edit box" when this View has a focus, which
            // confuses users on app launch (issue 5275935).
            return;
        }
        super.sendAccessibilityEventUnchecked(event);
    }

    /**
     * Interface to get callback from the Edittext copy, cut and paste event
     * For time being only the Paste Event callback is generated
     */
    public interface OnEditTextActionListener {

        /**
         * If Edittext get paste event then this method will be called
         */
        void onPaste();
    }

}

In your xml you can give like this,

<[package name].KeypadlessKeypad
        android:id="@+id/dialnumbertv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#00000000"
        android:cursorVisible="false"
        android:ellipsize="start"
        android:gravity="center"
        android:inputType="phone"
        android:singleLine="true"
        android:textIsSelectable="true"
        android:textSize="30sp"
        android:textStyle="italic"
        android:visibility="visible"/>

And in your fragment you can implement like this,

   public void onViewCreated(final View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mDialNumbertv = view.findViewById(R.id.dialnumbertv);

        mDialNumbertv.setCursorVisible(false);

        mDialNumbertv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isDigitsEmpty()) {
                    mDialNumbertv.setCursorVisible(true);
                }
            }
        });

        mDialNumbertv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (isDigitsEmpty()) {
                    mDialNumbertv.setCursorVisible(false);
                }
//                updateDeleteButton();
            }
        });

        mDialNumbertv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                // Ref https://android.googlesource.com/platform/packages/apps/Contacts/+/39948dc7e34dc2041b801058dada28fedb80c388/src/com/android/contacts/dialpad/DialpadFragment.java
                // Right now EditText does not show the "paste" option when cursor is not visible.
                // To show that, make the cursor visible, and return false, letting the EditText
                // show the option by itself.
                mDialNumbertv.setCursorVisible(true);
                return false;
            }
        });

        mDialNumbertv.setOnEditTextActionListener(
                new KeypadlessKeypad.OnEditTextActionListener() {
                    @Override
                    public void onPaste() {
                        // If some content pasted on mDialNumbertv
                        // we need to run some search on Contact and Price

                        String mobileNumber = mDialNumbertv.getText().toString();

                        if (TextUtils.isEmpty(mobileNumber)) {
                            return;
                        }

//                        updateContactName(mobileNumber);
                    }
                });

    }

    private KeypadlessKeypad mDialNumbertv;

    private boolean isDigitsEmpty() {
        return mDialNumbertv.length() == 0;
    }

    private void setClickedDigit(final String digitToSet) {
        if (!TextUtils.isEmpty(digitToSet)) {

            char digit = digitToSet.charAt(0);

            String mobileNumber = mDialNumbertv.getText() + digitToSet;
            mDialNumbertv.getText().insert(mDialNumbertv.getSelectionStart(), digitToSet);

            // If the cursor is at the end of the text we hide it.
            final int length = mDialNumbertv.length();
            if (length == mDialNumbertv.getSelectionStart() && length == mDialNumbertv.getSelectionEnd()) {
                mDialNumbertv.setCursorVisible(false);
            }
        }
    }

这篇关于即使EditText不可编辑,EditText游标也是可见的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆