2017-01-09 3 views
0

Я хочу сделать TextView выглядит следующим образомAndroid TextView вырезать часть письма, если текст слишком длинный

Two TextViews, one under another

где черная часть является TextView с меньшей шириной над серым. Это своего рода индикатор прогресса. Интересная часть заключается в том, что этот подход работает на 6.0.1, и он работал на 5.1.1 без каких-либо особых предпочтений. Но он перестал работать на леденец без каких-либо изменений в коде, и теперь TextView показывает только полные письма, не разрезая на части (например, в этом случае черный текст будет только «Или»)

Отредактировано:

Компоновка кода :

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:paddingRight="8dp" 
android:paddingLeft="8dp"> 
<TextView 
    android:text="Text" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/title" 
    android:textColor="@color/grey" 
    android:textSize="15sp" 
    android:textStyle="bold" 
    android:lines="1" 
    android:maxLines="1" /> 
<TextView 
    android:text="Text" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/titleselected" 
    android:textStyle="bold" 
    android:textSize="15sp" 
    android:textColor="@android:color/black" 
    android:lines="1" 
    android:maxLines="1" /> 
</RelativeLayout> 

Изменение прогресса:

titleSelected.LayoutParameters = new RelativeLayout.LayoutParams(Width, ViewGroup.LayoutParams.WrapContent); 
+0

, пожалуйста, поделитесь своим кодом –

ответ

0

где черная часть является TextView с меньшей шириной над серым. Это своего рода индикатор прогресса.

Вместо изменения layout_width из TextView, вы можете изменить right из TextView «s ClipBounds, как показано ниже:

[Activity(Label = "ChangingText", MainLauncher = true, Icon = "@drawable/icon")] 
public class MainActivity : Activity 
{ 
    Button btnClick; 
    TextView titleselected; 
    Rect drawingRect; 
    int width; 
    protected override void OnCreate(Bundle bundle) 
    { 
     base.OnCreate(bundle); 

     SetContentView (Resource.Layout.Main); 
     btnClick = FindViewById<Button>(Resource.Id.btnClick); 
     titleselected = FindViewById<TextView>(Resource.Id.titleselected); 
     width = 1; 
     btnClick.Click += BtnClick_Click; 
    } 

    private void BtnClick_Click(object sender, System.EventArgs e) 
    { 
     if (drawingRect == null) { 
      drawingRect = new Rect(); 
      titleselected.GetDrawingRect(drawingRect); 
     } 
     titleselected.ClipBounds = new Rect(0, 0, width++, drawingRect.Bottom); 
    } 
} 

И Main.axml:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:paddingRight="8dp" 
    android:paddingLeft="8dp"> 

<TextView 
    android:text="Text" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/title" 
    android:textColor="#C1C7C9" 
    android:textSize="15sp" 
    android:textStyle="bold" 
    android:lines="1" 
    android:maxLines="1" /> 
<TextView 
    android:text="Text" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/titleselected" 
    android:textStyle="bold" 
    android:textSize="15sp" 
    android:textColor="@android:color/black" 
    android:lines="1" 
    android:maxLines="1" /> 
<Button 
    android:id="@+id/btnClick" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="Click Me" 
    android:layout_marginTop="50sp" /> 
</RelativeLayout> 

И это хорошо работает.

+0

Да, это работает. Мне пришлось вызвать 'View.Invalidate()' после изменения 'ClipBounds', чтобы увидеть результат на устройстве. – Ilia

0

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

import android.app.Activity; 
import android.graphics.Canvas; 
import android.graphics.Picture; 
import android.graphics.Rect; 
import android.graphics.Region; 
import android.graphics.drawable.Drawable; 
import android.graphics.drawable.PictureDrawable; 
import android.os.Bundle; 
import android.text.Spannable; 
import android.text.SpannableStringBuilder; 
import android.text.TextPaint; 
import android.text.style.DynamicDrawableSpan; 
import android.text.style.ForegroundColorSpan; 
import android.widget.TextView; 

public class Sample extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.acitivity_sample); 
    TextView tv = (TextView) findViewById(R.id.textView1); 
    Spannable text = new SpannableStringBuilder("Loading.."); 
    setSpan(tv, text); 
    tv.setText(text); 
} 

private void setSpan(TextView tv, Spannable text) { 
    int blueColor = 0xff0000ff; 
    int redColor = 0xffff0000; 
    ForegroundColorSpan blue = new ForegroundColorSpan(blueColor); 
    ForegroundColorSpan red = new ForegroundColorSpan(redColor); 
    HalfColorApply o = new HalfColorApply("o", tv, blueColor, redColor); 
    text.setSpan(blue, 0, 1, 0); 
    text.setSpan(o, 1, 2, 0); 
    text.setSpan(red, 3, text.length(), 0); 
} 

class HalfColorApply extends DynamicDrawableSpan { 
    private final static String TAG = "DrawableSpanTest"; 
    Picture mPicture; 

    public HalfColorApply(String text, TextView tv, int c0, int c1) { 
     super(ALIGN_BASELINE); 
     mPicture = new Picture(); 
     TextPaint p = tv.getPaint(); 
     Rect bounds = new Rect(); 
     p.getTextBounds(text, 0, text.length(), bounds); 
     float width = p.measureText(text); 
     float height = bounds.height(); 
     float y = height; 
     Canvas c = mPicture.beginRecording((int) width, (int) height); 
     c.save(Canvas.CLIP_SAVE_FLAG); 
     // c.drawColor(0x[masked]); 
     p = new TextPaint(p); 
     p.setColor(c0); 
     c.clipRect(0, 0, width/2, height, Region.Op.REPLACE); 
     c.drawText(text, 0, y, p); 
     p.setColor(c1); 
     c.clipRect(width/2, 0, width, height, Region.Op.REPLACE); 
     c.drawText(text, 0, y, p); 
     c.restore(); 
     mPicture.endRecording(); 
    } 

    @Override 
    public Drawable getDrawable() { 
     PictureDrawable d = new PictureDrawable(mPicture); 
     d.setBounds(0, 0, mPicture.getWidth(), mPicture.getHeight()); 
     return d; 
    } 
} 
} 
+0

Да, spannable string дает нам возможность изменять стиль для символов, но мне нужно иметь наполовину черное письмо и еще одну половину серого. – Ilia

+0

@llia Я обновил свой ответ и попробовал это – HsRaja

+0

@llia проверить этот код, и я сделал это programtically – HsRaja