2010-08-31 121 views
1

我需要將多個ImageView加載到佈局。 ImageViews用於顯示使用'star'圖標的評分。恆星(即等級的數量由讀取配置文件加載期間確定將多個ImageView添加到佈局

的ImageViews正坐在一個RelativeLayout的佈局裏面

目前我使用的是這樣的:。

RelativeLayout l = ((RelativeLayout)(findViewById(R.id.RelativeLayout01))); 
for (int nStarCount = 0; nStarCount < config.getAsInt("stars", 1); nStarCount ++) { 
    ImageView image = new ImageView(this); 
    image .setImageResource(R.drawable.star); 
    image .setAdjustViewBounds(true); 
    l.addView(i); 
} 

我的問題是:

1)是做動態加載(不使用XML)是這樣做的'正確的方式?

2)如果是這樣,我該如何讓星星排成一行,目前他們將一個放在另一個的上面。

任何幫助,將不勝感激。

RM

+0

你有什麼需要在這篇文章中,? – 2011-08-17 07:47:47

回答

0

1)沒問題。儘管大多數人更喜歡XML。

2)將它們與定位一個LinearLayout中設置爲臥式

+0

但是如果我不知道有多少星星會在那裏,我怎麼能用XML來實現呢? Isnt移動他們到一個LinearLayout廢墟相對於其他佈局的方向? (這就是爲什麼我使用relativelayout) – 2010-08-31 15:28:32

+0

答:你不:)。 LinearLayout應該沒問題。佈局的類型隻影響其內容,在這裏線性很好。 – fredley 2010-08-31 15:33:12

+0

你說它的「很好的任何一種方式」,你可以提供一個例子如何做到這一點與XML? – 2010-08-31 15:34:49

1

對於您所創建的,我不認爲動態的觀點有什麼不妥通過代碼來這樣做。但是,如果您更願意通過xml進行佈局,則可以這樣做,然後調整代碼的可見性。即:

<RelativeLayout ...> 
    ... stuff goes here 
    <LinearLayout ..(setup where you want this 
    orienation="horizontal"> 
    <ImageView id="@+id/star1" 
     android:src="@drawable/star" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"/> 
    <ImageView id="@+id/star2" 
     android:src="@drawable/star" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"/> 
    <ImageView id="@+id/star3" 
     android:src="@drawable/star" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"/> 
    <ImageView id="@+id/star4" 
     android:src="@drawable/star" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"/> 
    <ImageView id="@+id/star5" 
     android:src="@drawable/star" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"/> 
    </LinearLayout> 
</RelativeLayout> 

的代碼實際上看起來多了幾分尷尬,因爲你需要通過id來解決每個明星ImageView的。

如果你做了很多的這些,你可以通過保存的ID到一個列表或東西使代碼少一點醜陋:

List<Integer> starIds = new List<Integer>(); 
starIds.add(R.id.star1); 
starIds.add(R.id.star2); 
... 

for (int x=starCount; x<5; x++) { 
    ImageView view = (ImageView)findById(starIds[x]); 
    view.setVisiblity(GONE); 
} 
3

如果你知道的明星,你會分配的最大數量,那麼你可以使用內置的RatingBar視圖。您的XML只是變成類似於:

<RatingBar android:id="@+id/ratingbar" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:numStars="5" 
    android:stepSize="1.0"/> 

在您的代碼中,請撥打ratingBar.setRating()來設置評級。如果您不想看到「空」星,您可以將最高評分和實際評分設置爲相同的數字。這樣,您可以節省重新實施相同小部件的麻煩。

請參閱:http://developer.android.com/resources/tutorials/views/hello-formstuff.html#RatingBar