DIRTY DAVE
DIRTY DAVE

Reputation: 2731

Can't see programatically inflated view

I'm trying to inflate and attach a view to it's parent layout, not sure what I'm doing incorrectly because I can't see the view displayed.

Parent Layout:

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

   <LinearLayout
       android:id="@+id/activity_main"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical"/>

</RelativeLayout>

Custom View:

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="@color/standardBlue">

</ImageView>

Inflating the view programmatically:

LinearLayout mCustomView = findViewById(R.id.activity_main);
View child = getLayoutInflater().inflate(R.layout.custom_imageview, null, false);
 mCustomView.addView(child);

Upvotes: 1

Views: 47

Answers (1)

akashzincle
akashzincle

Reputation: 1128

You can not add child views to views, you can add child views only to ViewGroups like LinearLayout, RelativeLayout, ConstraintLayout, FrameLayout (All are extending ViewGroup https://developer.android.com/reference/android/view/ViewGroup), but you can not add child views to ImageView, TextView, CHeckedTextView (All are extending View class https://developer.android.com/reference/android/view/View)

Here you are adding child views to your custom view ImageView.

Upvotes: 1

Related Questions