Android选择并突出显示EditText中的文本 [英] Android select and highlight text in edittext

查看:85
本文介绍了Android选择并突出显示EditText中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个具有EditText或TextView的应用程序,可在单击并突出显示选定的文本时将其选中.我怎样才能做到这一点?我尝试在EditText上覆盖onClick方法,但似乎无法正常工作.

I would like to do an app which has an EditText or TextView that can be selected upon click and highlight the selected text. How can I do that? I tried overriding onClick method on my EditText but seems not working.

这是我到目前为止尝试过的:

Here's what I've tried so far:

etx.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {

            int startSelection = etx.getSelectionStart();
            int endSelection = etx.getSelectionEnd();

            //String selectedText = etx.getText().toString().substring(startSelection, endSelection);

            Spannable spannable=new SpannableString(etx.getText().toString());
            spannable.setSpan(new ForegroundColorSpan(Color.BLUE), startSelection, endSelection, 0);
            etx.setText(spannable); 

            return true;
        }

    });



 <EditText 
        android:id="@+id/tvOrdinanceTitle" 
        android:layout_width="wrap_content" 
        android:textColor="@android:color/black"
        android:cursorVisible="false"
        android:layout_height="wrap_content"
        android:background="#00000000" > 
        </EditText>

但是它不起作用.任何解决方法?非常感谢您的帮助.谢谢.

But it's not working. Any workaround? I would gladly appreciate your help. Thanks.

推荐答案

您可以将其包含在.xml中:

You can include in your .xml:

android:selectAllOnFocus="true"

特别是:

android:textIsSelectable=Indicates that the content of a non-editable text can be selected. 
android:selectAllOnFocus=If the text is selectable, select it all when the view takes. focus. 

或以编程方式:

etx.setOnFocusChangeListener(new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
    if(hasFocus)
    { 
        etx.setSelection(editText.getText().toString().length());
    }
}
});

并标识要使用的颜色.可以说这是您的editText:

And to identify what colors to be used. Lets say this is your editText:

    <EditText 
    android:id="@+id/tvOrdinanceTitle" 
    android:layout_width="wrap_content" 
    android:cursorVisible="false"
    android:layout_height="wrap_content"
    android:background="@color/etxt_color" > 
    </EditText>

然后创建res/color/etxt_color.xml

Then create res/color/etxt_color.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
       android:color="#000000" /> <!-- pressed -->
 <item android:state_focused="true"
       android:color="#000000" /> <!-- focused -->
 <item android:color="#FFFFFF" /> <!-- default -->
 </selector>

这篇关于Android选择并突出显示EditText中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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