I have a custom view class extended from view and I want to use it in an activity but it doesn’t show anything. there are no errors it runs but black screen no output. My code is as follow:
public class MoveableMenuLayout extends View {
public MoveableMenuLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LinearLayout ll = new LinearLayout(context);
ll.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
TextView tv = new TextView(context);
tv.setText("TES_______________");
ll.addView(tv);
this.invalidate();
this.requestLayout();
}
public MoveableMenuLayout(Context context) {
super(context);
LinearLayout ll = new LinearLayout(context);
ll.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
TextView tv = new TextView(context);
tv.setText("TES_______________");
ll.addView(tv);
this.invalidate();
this.requestLayout();
}
}
CALLING ACTIVITY
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MoveableMenuLayout layout = new MoveableMenuLayout(this);
setContentView(layout);
}
}
I have tried it by including it in xml layout but still no output. I am not sure what I am doing wrong. I dont want to change the style I want it to be a separate class, I know I can use xml layout and set it directly in Activity with setcontentview but I don’t want to do that way. Thanks
Why would it- you have no data. You created a linear layout and text view, but they aren’t your children. So you have no data to draw (and haven’t overridden onDraw anyway).
If you want to create a custom view that holds a set of other views, you need to derive from ViewGroup, not View. You also need to add the top level subview(s) as children, not just hold them as data members. You’re probably even better off deriving directly from LienarLayout or RelativeLayout, and inflating your children directly from xml.
}
Will probably work. You can upgrade that to definitely by deriving from LinearLayout instead. And then you wouldn’t need to have an internal layout. Like this:
}
An even better way is to do it via xml
}
and then put the children you want in an xml file. In this case, the top level tag in the xml file should be a tag, not a layout