Adding ImageView to the Layout programmatically

前端 未结 2 400
忘掉有多难
忘掉有多难 2021-01-13 10:05

I want to create images which will go down from the upper part of the screen.

For up to today I have this:

ImageView mario = (ImageView) findViewById         


        
相关标签:
2条回答
  • 2021-01-13 10:47

    You can create a layout with something like

    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);
    

    What parameters you pass in layout() are obviously going to depend on what you want. Then you can create separate Views to add to the Layout you just created. But I highly advise reading through the docs to understand what all can be done here.

    ViewGroup

    View

    Edit

    ImageView myImage = new ImageView(this);
    picLL.addView(myImage);
    //set attributes for myImage;
    
    0 讨论(0)
  • 2021-01-13 10:51

    Using following code you can add image dynamically

    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); 
    
     }
    }
    
    0 讨论(0)
提交回复
热议问题