Create custom views that accept other layouts in xml attributes
I have an open-ended question that I am trying to resolve and I could find a possible solution that is less error prone; however I don't know how to code the solution.
The solution will be very similar to how it android.support.design.widget.NavigationView
handles the header representation in XML! The only problem is I tried to find the source code for NavigationView
, but I cannot find it. I can find other Android source code easily - apart from the new Design Library.
If I can find the Source Code from Google then I can implement something like this.
code
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/drawer"
app:headerLayout="@layout/drawer_header" />
Look at the last line? I want to be able to do something like this for my own customView in order to insert another view into it.
So my question is:
-
Where is the source code for the Design Library navigation bar?
OR
-
Is there another custom view that allows you to insert web-hosted layouts into it?
OR
-
If there is nothing on the Internet, then how will a person do it? Maybe. NavigationView does this.
source to share
Here's an example of how you can do it:
Q resources.xml
:
<declare-styleable name="MyCustomView">
<attr name="child_view" format="reference" />
</declare-styleable>
In MyCustomView.java
:
public class MyCustomView extends ViewGroup {
public MyCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyCustomView, 0, 0);
int childView = a.getResourceId(R.styleable.MyCustomView_child_view, R.layout.default_child_view);
a.recycle();
LayoutInflater.from(context).inflate(childView, this, true);
}
}
In your layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<your.package.MyCustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom_view:child_view="@layout/some_layout" />
</LinearLayout>
source to share