0xh8h
0xh8h

Reputation: 3509

How to create new Custom View object

I've create a Custom View. Now I want to create a class that has some Custom View as components (array of Custom View maybe). For example, something like Button b = new Button(this), how can I apply it for my custom view?

Because the constructor of custom view is CustomView(Context context, AttributeSets attrs), and in the new class that I created, I don't have context or attrs?

Thank you!

Upvotes: 1

Views: 7210

Answers (1)

Vikram
Vikram

Reputation: 51571

Add this constructor to your custom view class:

public CustomView(Context context) {
    mContext = context
}

This is how you would use the custom view:

If you need the custom view to be the only view:

CustomView cv = new CustomView(this);
setContentView(cv);

If you want to add custom view to a parent view:

// inflate mainXML
View mainView = getLayoutInflater().inflate(R.layout.mainXML, null);

// find container
LinearLayout container = (LinearLayout) mainView.findViewById(R.id.container);

// initialize your custom view
CustomView view = new CustomView(this);

// add your custom view to container
container.addView(view);

setContentView(mainView);

By the way, this should work too:

CustomView cv = new CustomView(this, null);

Edit 1:

Use nested for-loops:

LinearLayout childLL;
CustomView cv

for (int i = 0; i < 8; i++) {
    childLL = new LinearLayout(this);
    for (int j = 0; j < 8; j++) {
        cv = new CustomView(this);
        // set LayoutParams
        childLL.addView(cv);
    }
    container.addView(childLL);
}

setContentView(container);

Upvotes: 1

Related Questions