Manuel
Manuel

Reputation: 15042

How to add a custom view to an activity?

I know this has been asked many times on SO, but somehow I don't get to the solution reading the existing answers.

The most simple thing, I want to add a custom view in an activity. The custom view MyView has a background color, as well as its subView. But the activity is just plain white and does not seem to display the custom view.

Why is that?

MainAcivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        MyView myView = findViewById(R.id.myView);        
    }
}

main_activity.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.myapp.MyView
        android:id="@+id/myView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>

MyView.java

public class MyView extends LinearLayout {

    public MyView(Context context) {
        super(context);
        init(context);
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {

        inflate(context, R.layout.my_view, this);
        subView = findViewById(R.id.subView);
        //...
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
    }
}

my_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#ff00ff"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <ImageView
        android:id="@+id/subView"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="#ff00ff"
        tools:ignore="ContentDescription" />

</LinearLayout>

Upvotes: 1

Views: 80

Answers (1)

Bracadabra
Bracadabra

Reputation: 3659

If you don't skip onLayout implementation in you snippet then you remove layout logic of your custom view, just don't override it:

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}

Upvotes: 2

Related Questions