user1696947
user1696947

Reputation: 159

Android custom view and visible button

I made my custom view and I want to add view.button, so I made this solution:

Public void onCreate(Bundle savedInstanceState)
{
    Button up;
    up = new Button(getApplicationContext());
    up.setText("ahoj");
    up.setHeight(100);
    up.setWidth(100);
    up.setTop(200);
    up.setLeft(100);
    LinearLayout layout = new LinearLayout(getApplicationContext());
    super.onCreate(savedInstanceState);
    setContentView(layout);

    myview view = new myview(this);
    layout.addView(view);

layout.addView(up);

I only see my view but no button. My view only draw some PNG file. Does anyone know where is the problem? Thanks much.

Upvotes: 0

Views: 390

Answers (2)

Sebastian Breit
Sebastian Breit

Reputation: 6159

You have the code right but in the wrong order. Try this:

Public void onCreate(Bundle savedInstanceState)
{
    Button up;
    LinearLayout layout = new LinearLayout(getApplicationContext());
    up = new Button(getApplicationContext());
    up.setText("ahoj");
    up.setHeight(100);
    up.setWidth(100);
    up.setTop(200);
    up.setLeft(100);




    myview view = new myview(this);
    layout.addView(view);
    layout.addView(up);

    setContentView(layout);
    super.onCreate(savedInstanceState);
}

Upvotes: 0

Aleks G
Aleks G

Reputation: 57316

The most likely reason is that your custom view is added with layout params MATCH_PARENT. It takes the whole of the layout and the button is not visible. Try instead adding your custom view with WRAP_CONTENT params:

MyView view = new myview(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LAYOUTParams.WRAP_CONTENT)
layout.addView(view, lp);

Upvotes: 3

Related Questions