2016-07-22 15 views
-1

我遇到過無法找到解決方案的問題。我有一個圓形佈局,我將隨機顏色設置爲背景。問題是,佈局是正方形而不是圓形。這是我的代碼:如果我以編程方式設置背景,則圓形佈局將變爲正方形

在res的橢圓形/抽拉

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="oval"> 
<size 
    android:width="@dimen/avatar_height" 
    android:height="@dimen/avatar_height" /> 
</shape> 

的顏色它位於抽拉/值/顏色

<integer-array name="avatar_colors"> 
    <item>@color/avatar_1</item> 
    <item>@color/avatar_2</item> 
    <item>@color/avatar_3</item> 
    <item>@color/avatar_4</item> 

</integer-array> 

陣列這是我的圓周佈置

<RelativeLayout 
         android:id="@+id/letter_avatar" 
         android:layout_width="@dimen/avatar_height" 
         android:layout_height="@dimen/avatar_height" 
         android:background="@drawable/avatar"> 

         <TextView 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content" 
          android:textSize="@dimen/textsize_splash_screen" 
          android:textColor="@color/jwhite" 
          android:layout_marginBottom="@dimen/gap_small" 
          android:text="A" 
          android:layout_centerInParent="true"/> 
        </RelativeLayout> 

這就是我如何設置隨機顏色作爲背景

mLetterAvatar = (RelativeLayout) findViewById(R.id.letter_avatar); 

    int[] androidColors = getResources().getIntArray(R.array.avatar_colors); 
     int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)]; 
     mLetterAvatar.setBackgroundColor(randomAndroidColor); 

這是我得到

enter image description here

注的結果:如果我不設置背景編程佈局具有圓形(見下面的屏幕截圖)

enter image description here

如何獲得圓形佈局並可選擇以編程方式添加背景色作爲背景?謝謝。

+0

您在drawable中設置的背景是圓形,您在代碼中設置的背景不是圓形的drawable。如果你想改變顏色,你應該使用色調或改變爲不同顏色的繪圖。 – Ramin

回答

1

的問題是,您使用的是普通的色彩搭配這條線替換您繪製背景:

mLetterAvatar.setBackgroundColor(randomAndroidColor); 

所以,如果你想改變圓圈的顏色相反,你應該有另一種形狀用不同的顏色,或者從代碼中獲取可繪製的顏色並設置顏色描述如下link

0

正如我所看到的,您將avatar.xml作爲背景放置在XML中,並在代碼中將avatar_color.xml [帶有隨機索引]。

+0

是的。這就是我所做的 –

+0

'setBackgroundColor'覆蓋了xml中設置的drawable,所以你的內部不是ShapeDrawable,而是ColorDrawable,因此你有方形背景,但不是圓形。 –

0

所以在一個忙碌的週末之後,我設法找到了一個基於Jonathan Aste答案的解決方案。我不知道這是否是最乾淨的方法,但它在這裏:

res/drawable我創建了4種不同背景顏色的不同形狀。

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="oval"> 

<solid android:color="#ffcc00"/> 
<size 
    android:width="@dimen/avatar_height" 
    android:height="@dimen/avatar_height" /> 

在那之後,我已經創造了這個數組中RES /價值/ arrays.xml。

<array name="random_avatar_array"> 
    <item>@drawable/avatar_green</item> 
    <item>@drawable/avatar_yellow</item> 
    <item>@drawable/avatar_red</item> 
    <item>@drawable/avatar_blue</item> 
</array> 

和代碼,這是我做了什麼

 if (view.getBackground() == null) { 
     TypedArray avatars = getResources().obtainTypedArray(R.array.random_avatar_array); 
     Drawable drawable = avatars.getDrawable(new Random().nextInt(avatars.length())); 
     view.setBackground(drawable); 
    } 

希望它可以幫助別人。

相關問題