Reputation: 835
I have extended a LinearLayout
which represents my main ui block and inside this I use two more extended LinearLayout
.
If i have to write it down with pseudo code is like this :
Bar extends LinearLayout
init() //here I initialize the LinearLayout and set some properties.
//the Constructor
public Bar(Context context, int height ) {
super(context);
this.context = context;
this.height = height;
init(); //calling init() inside the constructor
}
and inside Bar the code is :
public void create() {
upLinearLayout = new UpLinearLayout(context, 40 );
downLinearLayout = new DownLinearLayout(context, 160);
this.addView(upLinearLayout);
this.addView(downLinearLayout);
}
So when I'm on my MainActivity I give :
Bar bb = new mBar(this, 300);
bar.create();
where create()
is :
public void create() {
upLinearLayout = new UpLinearLayout(context, 40 );
downLinearLayout = new DownLinearLayout(context, 160);
this.addView(upLinearLayout);
this.addView(downLinearLayout);
}
So far the code is working great. But I cannot call from Bar methods that belong to upLinearLayout or downLinearLayout e.g. :
public void anotherButton(Context context) {
Button button1 = new Button(context);
button1.setText("Testing");
button1.setTextSize(18);
this.addView(button1);
}
Now inside the Bar class I can't do:
UpLinearLayout up = new UpLinearLayout(context, 65);
up.anotherButton(context);
it gives me error :
Error:(47, 11) error: cannot find symbol method anotherButton(Context)
tl;dr In MainActivity I can call all public methods of Bar
- but I can't do the same inside extended Bar
for other extended classes.
What I can do is only initialize them.
Upvotes: 1
Views: 68
Reputation: 157457
Now inside the Bar class I can't do:
UpLinearLayout up = new UpLinearLayout(context, 65);
up.anotherButton(context);
you can't because anotherButton
is a method of Bar
, but you are calling on an instance of UpLinearLayout
which has not a method call anotherButton
. If you want to add a Button
to UpLinearLayout
from bar you could do:
public void anotherButton(LinearLayout layout) {
Button button1 = new Button(getContext());
button1.setText("Testing");
button1.setTextSize(18);
layout.addView(button1);
}
and then call it like anotherButton(up);
or add anotherButton
in UpLinearLayout
. And don't forget to cast to the exact type if you declared your member with the Base class. E.g.
You declared
LinearLayout upperLayout;
if you want to access a method of your custom
UpperLinearLayout extend LinearLayout
you have to cast upperLayout
explicitly to UpperLinearLayout
Upvotes: 1