Reputation: 2025
I am crossing from the iOS development and I am trying to figure out how to create reusable component. eg Having a two buttons.
I could always create the two buttons every time but then I would end up with repeated code.
So can I have just one view type and access properties of each button separately so I can set title, font, onClick action.
I have tried looking over here but could not get anything. Any material or sample to help would be helpful for someone like me coming from iOS development.
Upvotes: 1
Views: 4675
Reputation: 13289
Try to create a custom layout for your buttons and style them as you need, let's call it custom_button_layout.xml
for example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
<!-- Apply your button style here -->
/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
<!-- Apply your button style here -->
/>
</LinearLayout>
In order to add custom text or properties in general to your button you should declare a custom style in your /res/values/attrs.xml
file (Create one if you don't have it in your project):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomButtonLayout">
<attr name="button1Text" format="string"/>
<attr name="button2Text" format="string"/>
</declare-styleable>
</resources>
Then create a custom view class extending the LinearLayout
superclass and assign to it the layout just created.
Handle the click event on the two buttons with the setOnClickListener
method and retrieve your custom stylable attributes in the constructor:
class CustomButtonLayout (
context: Context,
attrs: AttributeSet
) : LinearLayout(context, attrs) {
init {
inflate(context, R.layout.example, this)
val customAttributesStyle = context.obtainStyledAttributes(attrs, R.styleable.CustomButtonLayout, 0, 0)
val button1 = findViewById<Button>(R.id.button1)
val button2 = findViewById<Button>(R.id.button2)
try {
button1.text = customAttributesStyle.getString(R.styleable.CustomButtonLayout_button1Text)
button2.text = customAttributesStyle.getString(R.styleable.CustomButtonLayout_button2Text)
} finally {
customAttributesStyle.recycle()
}
button1.setOnClickListener {
// Handle button1 click event...
}
button2.setOnClickListener {
// Handle button2 click event...
}
}
}
Finally, use your custom button in your XML layouts with its custom tag and attributes:
<CustomButtonLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:button1Text="Button 1 text"
app:button2Text="Button 2 text"/>
Upvotes: 10