Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: a newby GUI question - how to declare viewGroup, without layout XML file?

In the app, I'm struggling with I have a custom view. I cannot declare it in layout XML file, because I'm going to use in from the activity that holds my custom view instance and I need to have access to it (cannot override findViewById...).

Thereof I decided to declare all of the GUI elements into the Activity.

But I simply cannot make a single step forward, since I even cannot instantiate viewGroup...

This is what I'm trying:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ViewGroup vg = new ViewGroup(this.getApplicationContext());

    setContentView(vg);

}

and I get 'Cannot instantiate ViewGroup'...

Can someone give a straight-forward example, of how to declare a viewGroup, that holds views?

The documentation of the class is also not very beginner-friendly... all the examples are focused on describing the layout in a layout XML file...?

Appreciate your efford, giving an example!

like image 952
karla Avatar asked Dec 04 '10 17:12

karla


1 Answers

[ViewGroup][1] is an abstract class, you cannot instantiate it. It defines a type of classes that will be container to put other views in them. In other words, layouts like LinearLayout of RelativeLayout are ViewGroup. Thus, you could do something like that :

   @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  LinearLayout vg = new LinearLayout(this);
// set the LayoutParams the way you want.
// and add textviews, imageviews, ... here for instance.
  setContentView(vg);

 }

For the LayoutParams, I think you should start with LayoutParams.Fill_parent

like image 91
Sephy Avatar answered Nov 02 '22 14:11

Sephy