2014-02-05 6 views
0

Мне нужно эллипсировать возможно длинное предложение по желаемому слову. Например, в предложении:Ellipsize textview по определенному слову

Здравствуйте, Стивен Хокинг, как вы поживаете?

Stephen Hawking - динамический текст, который может быть сколь угодно длинным. Я хотел бы усечь это слово, а не другие:

Привет, Ste ..., как вы поживаете?

Android TextUtils предлагает перечисление для усечения, но я не вижу, чтобы проблема была решена. Может ли быть другой способ? Я просто знаю, что положение слова усекается.

+1

почему бы не использовать два TextViews – user2450263

+0

динамический текст, вы имеете в виду с этим я пришел с переменной в коде или что? –

+0

Динамический смысл текста, я не знаю этого слова заранее. Он исходит от серверного сервера. – SlowAndSteady

ответ

0

Два TextViews бы обеспечить простое и эффективное решение в этом случае.

1 для «Hello NameHere» и второй для остальной части текста.

Может указывать требуемый эллипсис для первого.
Оптимально с наименьшими накладными расходами для требуемого выхода.

1

Этот код использовать полный для вас ..

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:padding="20dp"> 

    <TextView 
     android:id="@+id/textView2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Hello " /> 

    <TextView 
     android:id="@+id/textView_Name" 
     android:layout_width="35dp" 
     android:layout_height="wrap_content" 
     android:layout_alignBaseline="@+id/textView2" 
     android:layout_alignBottom="@+id/textView2" 
     android:layout_toRightOf="@+id/textView2" 
     android:ellipsize="end" 
     android:singleLine="true" 
     android:text="Stephen Hawking" /> 

    <TextView 
     android:id="@+id/textView3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignBaseline="@+id/textView_Name" 
     android:layout_alignBottom="@+id/textView_Name" 
     android:layout_toRightOf="@+id/textView_Name" 
     android:text=", " /> 

    <TextView 
     android:id="@+id/textView_Other" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignBottom="@+id/textView3" 
     android:layout_toRightOf="@+id/textView3" 
     android:text="how are you doing ?" /> 

</RelativeLayout> 
1

Попробуйте испытания рабочего раствора

import android.app.Activity; 
import android.os.Bundle; 
import android.view.ViewTreeObserver; 
import android.view.ViewTreeObserver.OnGlobalLayoutListener; 
import android.widget.TextView; 

public class MainActivity extends Activity { 


    TextView txtView; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     txtView = (TextView) findViewById(R.id.txtView); 
     txtView.setText("Hello Stephen Hawking, how are you doing ?Are you fine dude?"); 
     doEllipsize(txtView, "Stephen Hawking"); 
    } 

    public void doEllipsize(final TextView tv, final String word) { 
     ViewTreeObserver vto = tv.getViewTreeObserver(); 
     vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 

      @SuppressWarnings("deprecation") 
      @Override 
      public void onGlobalLayout() { 

       ViewTreeObserver obs = tv.getViewTreeObserver(); 
       obs.removeGlobalOnLayoutListener(this); 

       if(tv.getLineCount()>1){ 
        String replacedString = tv.getText().toString().replace(word, word.substring(0, 3)+"..."); 
        tv.setText(replacedString); 
       } 

      } 
     }); 
    } 
} 

Выход:

enter image description here

+0

Спасибо, но это будет эллипсизировать предложение каждый раз. Мне нужен эллипс только тогда, когда текст достаточно длинный, чтобы не укладываться в одну строку (что опять зависит от устройства). Вот как работает эллипсис Android ... – SlowAndSteady

+0

ok Я просто обновляю вас, когда решаю –

0

Чтобы воспользоваться принятым ответом пользователя2450263, приведен пример. Как мой комментарий указывает ниже, я использовал атрибут layout_weight, чтобы заставить LinearLayout измерять дважды. Без этой части слово справа будет вытолкнуто с экрана, если основной текст будет эллипсирован.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 

    <!-- Using a weight to force the LL to measure twice --> 
    <TextView 
     android:id="@+id/main_text" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:ellipsize="end" 
     android:singleLine="true" /> 

    <TextView 
     android:id="@+id/suffix" 
     android:layout_marginLeft="3dp" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 

</LinearLayout> 

Если это не работает для вас, или если вам нужно сделать это в куче разных мест, где вы также можете создать свой собственный виджет.


Вот как вы это сделаете.
Пользовательский вид:

public class EllipsizedTextViewWithSuffix extends LinearLayout { 

    private TextView mainText, suffix; 

    public EllipsizedTextViewWithSuffix(Context context) { 
     this(context, null); 
    } 

    public EllipsizedTextViewWithSuffix(Context context, AttributeSet attrs) { 
     this(context, attrs, 0); 
    } 

    public EllipsizedTextViewWithSuffix(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 

     init(context); 
    } 

    private void init(Context context) { 
     inflate(context, R.layout.ellipsized_tv_with_suffix, this); 
     mainText = (TextView) findViewById(R.id.main_text); 
     suffix = (TextView) findViewById(R.id.suffix); 
    } 

    public void setText(String mainText, String suffix) { 
     this.mainText.setText(mainText); 
     this.suffix.setText(suffix); 
    } 
} 

Компоновка файл (ellipsized_tv_with_suffix.xml):

<?xml version="1.0" encoding="utf-8"?> 
<merge xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal"> 

    <!-- Using a weight to force the LL to measure twice --> 
    <TextView 
     android:id="@+id/main_text" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:ellipsize="end" 
     android:singleLine="true" /> 

    <TextView 
     android:id="@+id/suffix" 
     android:layout_marginLeft="3dp" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 

</merge> 

И затем использовать его вам просто нужно добавить его в другую раскладку.
Замените, пожалуйста, правильное название пакета.

<your.package.name.EllipsizedTextViewWithSuffix 
    android:id="@+id/ellipsized_tv" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 
Смежные вопросы