I'm new to Android Development.
Is it possible to change a View inside an included layout using custom attribute?
I mean like this:
This is my_layout
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listItem"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/userImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="..." />
<!-- this src attribute can be overrided using my own attribute in the iclude tage -->
<TextView
android:id="@+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="..." />
<!-- this text attribute can be overrided using my own attribute in the iclude tage -->
</LinearLayout>
and this is how I want to include my_layout
to the activity layout:
<include layout="@layout/my_layout" userName="@string/userName1" userImage="@drawable/userImage1"/>
userName
and userImage
override the value of android:text
and android:src
attribute.
I have read about Data Binding but what I mean here is not using any Java class. I just need to define a variable into data tag in my_layout
with type
value referenced to @string/
or @drawable/
to get a text or picture.
Is it possible?
As your description, you want to post userName1
and userImage1
to the View in my_layout
. You can not make it. And the way you use the custom view is wrong. The tag 'include' is also not custom tag.
You can use custom attribute follow this sample:
<com.amscf.view.InviteItemView
android:id="@+id/invite_item_instagram"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="@drawable/item_color"
android:paddingBottom="10dp"
android:paddingTop="10dp"
app:appicon="@drawable/icon_app_instagram"
app:btntext=""
app:coindesc="Post a invitation"
app:cointext="Share to Instagram"
app:showweek="false"/>
In the view InviteItemView
you can get the attibute appIcon
, btnText
with below code:
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.invite_item_view);
int refId = typedArray.getResourceId(R.styleable.invite_item_view_appicon, R.mipmap.ic_launcher);
String btnText = typedArray.getString(R.styleable.invite_item_view_btntext);
the refId
and btnText
is what you will get.
Add the below code to your attrs.xml
, this is the definition of invite_item_view
<declare-styleable name="invite_item_view">
<attr name="appicon" format="reference"/>
<attr name="cointext" format="string"/>
<attr name="coindesc" format="string"/>
<attr name="btntext" format="string"/>
<attr name="showweek" format="boolean"/>
</declare-styleable>