Skip to content

Instantly share code, notes, and snippets.

@jkreiser
Created February 25, 2014 16:18
Show Gist options
  • Save jkreiser/9212155 to your computer and use it in GitHub Desktop.
Save jkreiser/9212155 to your computer and use it in GitHub Desktop.
Android - Custom Component - Caption Button
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CaptionButton">
<attr name="button_icon" format="reference" />
<attr name="caption" format="reference|string" localization="suggested" />
</declare-styleable>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/linearLayout">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton_icon"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Caption"
android:id="@+id/textView_caption"
android:gravity="center_horizontal"/>
</LinearLayout>
package com.yourpackagename;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.yourpackagename.R;
public class CaptionButton extends LinearLayout {
ImageButton imageButton_icon;
TextView textView_caption;
public CaptionButton(Context context) {
super(context);
}
public CaptionButton(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.caption_button, this);
imageButton_icon = (ImageButton) findViewById(R.id.imageButton_icon);
textView_caption = (TextView) findViewById(R.id.textView_caption);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CaptionButton);
Drawable icon = a.getDrawable(R.styleable.CaptionButton_button_icon);
String caption = a.getString(R.styleable.CaptionButton_caption);
a.recycle();
setIcon(icon);
setCaption(caption);
}
public void setIcon(Drawable icon) {
imageButton_icon.setImageDrawable(icon);
}
public void setCaption(String caption) {
textView_caption.setText(caption);
}
@Override
public void setOnClickListener(OnClickListener onClickListener) {
imageButton_icon.setOnClickListener(onClickListener);
}
}
xmlns:my_app="http://schemas.android.com/apk/res-auto"
<com.yourpackagename.CaptionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
my_app:button_icon="@drawable/message_icon"
my_app:caption="@string/message_caption"/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment