开发者

Set a new view's margins programatically

I have a FrameView that's created in my XML layout, and in my code, I'm trying to create a series of new ImageViews and add them as children of this FrameView. The ImageViews are small, only about 15 pixels square, and I want them to show up in various positions around the FrameView (I'm trying to implement what looks like a radar screen). I'm able to create them and add them just fine, and they show up on the screen. However, when I try to set their margins, it doesn't seem to have any effect. No matter what I set, all the ImageViews show up in the top left corner of the FrameView, as opposed to offset by the appropriate margins. My XML layout is listed below, along with the code that generates the child views. Am I doing something wrong? How can I get the margins to show up properly? Or is there a better way to do this than by using margins.

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/RadarBackground"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="@drawable/radar_bg">
 <FrameLayout 
   android:id="@+id/RadarFrame" 
   android:layout_width="320dip" 
   android:layout_height="320dip" 
   android:layout_marginTop="25dip">
 </FrameLayout>
</LinearLayout>开发者_如何学编程;

Java:

for (int i = 0; i < getData().getTargetCount(); i ++) {
 int id = getData().getTargetId(i);
 Log.d(T.TAG_A, "Radar: plotting target " + id);
 TargetView tv = new TargetView(this, id, getData().getTargetName(id));
 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
   LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
 lp.setMargins(
   radarCenterX + (int) (getData().calcTargetRadarX(id, radarSize) / radarScale) - (targetSizeX / 2), 
   radarCenterY - (int) (getData().calcTargetRadarY(id, radarSize) / radarScale) - (targetSizeY / 2), 
   0, 0);
 tv.setImageResource(R.drawable.radar_civilian);
 tv.setOnClickListener(this);
 mTargets.add(tv);
 mFrame.addView(tv, lp);
}


FrameLayout does not consider the margin parameters if you don't specify the view Gravity. Try specifying the gravity for all the ImageViews.

HTH !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜