Skip to content

Instantly share code, notes, and snippets.

@Zhuinden
Created January 30, 2017 14:38
Show Gist options
  • Save Zhuinden/e975e45f9133724d86595367345f3331 to your computer and use it in GitHub Desktop.
Save Zhuinden/e975e45f9133724d86595367345f3331 to your computer and use it in GitHub Desktop.
Custom ViewGroup example
public class MyCustomViewGroup extends RelativeLayout {
public MyCustomViewGroup(Context context) {
super(context);
init(context);
}
public MyCustomViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MyCustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
@TargetApi(21)
public MyCustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
private void init(Context context) {
if(!isInEditMode()) {
// ...
}
}
@OnClick(R.id.button)
public void doSomething() {
// ...
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
ButterKnife.bind(this);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
// pretty much `onStart()`
}
@Override
protected void onDetachedFromWindow() {
// pretty much `onStop()`
super.onDetachedFromWindow();
}
}
<?xml version="1.0" encoding="utf-8"?>
<fully.qualified.MyCustomViewGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Go to next"/> <!-- centerInParent works because -->
<!-- custom viewgroup is also RelativeLayout -->
</fully.qualified.MyCustomViewGroup>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment