So the first thing that you will have to do is edit your attrs.xml file. Here you will add all of the attributes that you want to define via xml. Here we have added a title, as well as right and left buttons with text and a drawable.
<declare-styleable name="activity_header">
<attr name="title" format="string" />
<attr name="left_button_text" format="string" />
<attr name="left_button_drawable" format="reference" />
<attr name="right_button_text" format="string" />
<attr name="right_button_drawable" format="reference" />
<attr name ="hide_buttons">
<enum name="yes" value="1" />
<enum name="no" value="0" />
</attr>
</declare-styleable>
Next you'll want to create your layout. The important thing here is to add a namespace that refers to your app. Here I have named it app. You just need to include your package name after http://schemas.android.com/apk/res/ . Now you can use any of the attributes you defined above in your xml file.
<
LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res/com.biggu.shopsavvy.ui4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<com.biggu.shopsavvy.ui4.ActivityHeader
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/header"
app:title = "History"
app:left_button_text="Share"
app:left_button_drawable="@drawable/ic_menu_share"
app:right_button_drawable="@drawable/small_btn_archive"
app:right_button_text="Organize" />
Now that we have our attributes defined in our xml file we need to retrieve them from our custom component that we have made. You should simply have to get the obtained style attributes using your resource that you created, here we used activity_header.
public class ActivityHeader extends LinearLayout {
TextView mTitleEditText;
Button mLeftButton;
Button mRightButton;
View mDelimeter;
private ViewGroup mAdditionalPanel;
public ActivityHeader(Context context, AttributeSet attrs) {
super(context, attrs);
ViewGroup.inflate(context, R.layout.header , this);
findViews();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.activity_header);
if ( a.getInt(R.styleable.activity_header_hide_buttons, 0) == 1) //hide buttons
{
mLeftButton.setVisibility(GONE);
mRightButton.setVisibility(GONE);
}
else
{
setLeftButtonDrawable(a.getResourceId(R.styleable.activity_header_left_button_drawable, android.R.drawable.ic_menu_info_details));
setLeftButtonText(a.getString(R.styleable.activity_header_left_button_text));
setRightButtonDrawable(a.getResourceId(R.styleable.activity_header_right_button_drawable, android.R.drawable.ic_menu_info_details));
setRightButtonText(a.getString(R.styleable.activity_header_right_button_text));
}
setTitle(a.getString(R.styleable.activity_header_title));
a.recycle();
}
}
That's it. Happy coding.