The java android.view ViewGroup addView() method is used to add a new child view to a ViewGroup. Here, ViewGroup is a base class for layouts and views containers which provide the ability to organize views into a hierarchy.
In this example, we use addView() method to add a new TextView to a linear layout. The linear layout is identified by its ID using method findViewById(). The text "Hello World!" is set to the TextView object and then added to the linear layout using addView() method.
Example 2: Adding an ImageView to a RelativeLayout
RelativeLayout relativeLayout = findViewById(R.id.relativeLayout); ImageView imageView = new ImageView(context); imageView.setImageResource(R.drawable.my_image); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); imageView.setLayoutParams(layoutParams); relativeLayout.addView(imageView);
In this example, we use addView() method to add a new ImageView to a relative layout. The relative layout is identified by its ID using method findViewById(). The image resource is set to the ImageView object and then added to the relative layout using addView() method. Also, we have set the layout parameters using the RelativeLayout.LayoutParams class, which allow us to specify how the child view should be positioned and sized within its parent view.
Package library: android.view.ViewGroup package.
Java ViewGroup.addView - 30 examples found. These are the top rated real world Java examples of android.view.ViewGroup.addView extracted from open source projects. You can rate examples to help us improve the quality of examples.