2010-08-31 105 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