2016-12-02 34 views
1

如果我想在TextView中像按照图像一样进行渐变,我应该怎么做?有什么想法或解决方案?如何为条形图提供背景层次

(渐变的宽度,长度取决于文本中的TextView值)

enter image description here

+0

只是''BackgroundColor'给'TextView'你的'梯度'。 – Ironman

+0

查看我的回答 –

回答

2

定义绘制资源文件中像这样

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 
    <gradient 
     android:angle="180" 
     android:endColor="@color/your_color" 
     android:startColor="@color/your_color2" 
     android:type="linear" /> 
</shape> 

,并以此为背景的查看

<FrameLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 

    <View 
     android:layout_width="match_parent" 
     android:layout_height="20dp" 
     android:id="@+id/view" 
     android:background="@drawable/your_gradient" 
     /> 

    <TextView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="30" 
    android:id="@+id/percentageTextview" 
    /> 

</FrameLayout> 

and on your activ ity使用这个

View background = (View) findViewById(R.id.view); 
TextView textView = (TextView) findViewById(R.id.percentageTextview); 

DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); 
int screenWidthInPix = displayMetrics.widthPixels; 

ViewGroup.LayoutParams params = background.getLayoutParams(); 
params.width = (screenWidthInPix * Integer.parseInt(textView.getText().toString()))/100; 
background.setLayoutParams(params); 
+0

非常感谢你! – wallah

相关问题