将imageView动态添加到线性布局上

时间:2012-09-27 07:19:07

标签: android

我是Android的新手。我有一个要求,我必须动态地将imageViews添加到线性布局,然后必须单独为每个图像设置动画。

我不知道将imageViews动态添加到线性布局的方法。 Plz帮助我。

由于

4 个答案:

答案 0 :(得分:6)

您可以像这样动态添加view

LinearLayout.LayoutParams imParams = 
    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ImageView imSex = new ImageView(context);
imSex.setImageResource(getmyImage());

mainlayout.addView(imSex,imParams);

答案 1 :(得分:1)

看到这个

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.rainbow);
    ImageView tv1 = new ImageView (this);
    tv1.setImageresorce(R.drawable.image1);
    ImageView tv2 = new ImageView (this);
    tv2.setImageresorce(R.drawable.image2);
    ImageView tv3 = new ImageView (this);

    tv3.setGravity(Gravity.CENTER);
    tv3.setImageresorce(R.drawable.image3);
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    ll.setGravity(Gravity.CENTER);
    ll.addView(tv1);
    ll.addView(tv2);
    ll.addView(tv3);
    setContentView(ll);
}

查看此有用数据

http://mobile.tutsplus.com/tutorials/android/android-layout/

答案 2 :(得分:1)

您可以试试这段代码。它还可以设置ImageView的尺寸以及多个ImageView's之间的边距。 int dimens = 45int dimensMargin = 4;的值为pixel,正在转换为dp。

LinearLayout linlaLikes必须位于您的布局XML中,然后投放到您的活动中。

LinearLayout linlaLikes = (LinearLayout) findViewById(R.id.linlaLikes);
ImageView imgUsers = new ImageView(getApplicationContext());

// SET THE IMAGEVIEW DIMENSIONS
int dimens = 45;
float density = getResources().getDisplayMetrics().density;
int finalDimens = (int)(dimens * density);

LinearLayout.LayoutParams imgvwDimens = new LinearLayout.LayoutParams(finalDimens, finalDimens);
imgUsers.setLayoutParams(imgvwDimens);

// SET SCALETYPE
imgUsers.setScaleType(ScaleType.CENTER_CROP);

// SET THE MARGIN
int dimensMargin = 4;
float densityMargin = getResources().getDisplayMetrics().density;
int finalDimensMargin = (int)(dimensMargin * densityMargin);

LinearLayout.LayoutParams imgvwMargin = new LinearLayout.LayoutParams(finalDimens, finalDimens);
imgvwMargin.setMargins(finalDimensMargin, finalDimensMargin, finalDimensMargin, finalDimensMargin);

// SET YOUR IMAGER SOURCE TO YOUR NEW IMAGEVIEW HERE

// ADD THE NEW IMAGEVIEW WITH THE PROFILE PICTURE LOADED TO THE LINEARLAYOUT
linlaLikes.addView(imgUsers, imgvwMargin);

答案 3 :(得分:0)

您可以为此http://developer.android.com/guide/components/fragments.html

使用片段
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragment imageFragment = new ExampleFragment();
fragmentTransaction.add(R.id.image_container, imageFragment);
fragmentTransaction.commit();