【问题标题】:Adding ImageView to the Layout programmatically以编程方式将 ImageView 添加到布局
【发布时间】:2013-02-26 19:48:28
【问题描述】:

我想创建从屏幕上部向下的图像。

到今天为止,我有这个:

ImageView mario = (ImageView) findViewById(R.id.mario);
TranslateAnimation anim = new TranslateAnimation(0f, 0f, 0, 400);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(800);
mario.startAnimation(anim);

问题是我必须在布局上的 xml 文件上设置 imageview,而这段代码只创建了 1 张图片。

我想对应用程序进行编程,以在屏幕的上部创建几个图像(例如在一个循环中),然后让它们下拉到屏幕上。 (这里我在这里使用 TranslateAnimation)。 我发现了这样的东西:

ImageView mario = (ImageView) findViewById(R.drawable.mario);

但我不知道如何设置不在 xml 文件中的 ImageView 的位置(可能吗?)。 我想创建 LinearLayout 并将其添加到 ImageView。但是如何将线性布局添加到现有布局中?

提前致谢:)

【问题讨论】:

    标签: android android-layout android-imageview


    【解决方案1】:

    您可以使用类似的东西创建布局

    View view = (View) findViewById(R.layout.current_layout); //the layout you set in `setContentView()`
    LinearLayout picLL = new LinearLayout(CurrentActivity.this);
    picLL.layout(0, 0, 100, 0);
    picLL.setLayoutParams(new LayoutParams(1000, 60));
    picLL.setOrientation(LinearLayout.HORIZONTAL);
    ((ViewGroup) view).addView(picLL);
    

    你传入layout() 的参数显然取决于你想要什么。然后您可以创建单独的Views 以添加到您刚刚创建的Layout。但我强烈建议通读文档以了解这里可以做什么。

    ViewGroup

    View

    编辑

    ImageView myImage = new ImageView(this);
    picLL.addView(myImage);
    //set attributes for myImage;
    

    【讨论】:

    • 最后一句 ((ViewGroup) view).addView(picLL); 不起作用,因为:“类型 ViewGroup 无法解析为类型”。还有为什么我们不使用view?最后一个问题——如何将 ImageView 添加到这个视图中?
    • ViewGroup 允许您向View 添加额外的项目。你可以试试View,但我不相信它会向它添加东西,但我会在几分钟后检查它。我将编辑我的答案以将ImageView 添加到布局中
    【解决方案2】:

    使用以下代码可以动态添加图片

    public class MainActivity extends Activity {
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     ImageView imageview = new ImageView(MainActivity.this);
     RelativeLayout relativelayout = (RelativeLayout)findViewById(R.id.relativeLayout);
     LinearLayout.LayoutParams params = new LinearLayout
     .LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    
     // Add image path from drawable folder.
     imageview.setImageResource(R.drawable.demo_new_image);
     imageview.setLayoutParams(params); 
     relativelayout.addView(imageview); 
    
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多