Skip to content

Instantly share code, notes, and snippets.

@ahmedre
Created March 21, 2016 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedre/5a6ccb964599a0634261 to your computer and use it in GitHub Desktop.
Save ahmedre/5a6ccb964599a0634261 to your computer and use it in GitHub Desktop.
Fallback default values for View styles
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SimpleView">
<attr name="android:color" />
</declare-styleable>
<attr name="SimpleViewStyle" format="reference" />
</resources>
public class SimpleView extends View {
final Paint paint = new Paint();
public SimpleView(Context context) {
this(context, null);
}
public SimpleView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.SimpleViewStyle);
}
public SimpleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray ta = context.obtainStyledAttributes(
attrs, R.styleable.SimpleView, defStyleAttr, R.style.SimpleViewDefaultStyle);
int color = ta.getColor(R.styleable.SimpleView_android_color, 0);
paint.setColor(color);
ta.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
boolean isRtl = ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL;
if (isRtl) {
canvas.save();
canvas.translate(getWidth(), 0);
canvas.scale(-1.0f, 1.0f);
}
canvas.drawRect(0, 0, 100, 100, paint);
if (isRtl) { canvas.restore(); }
}
}
<?xml version="1.0" encoding="utf-8"?>
<com.cafesalam.experiments.app.ui.SimpleView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<resources>
<style name="SimpleViewDefaultStyle">
<item name="android:color">#ffff0000</item>
</style>
</resources>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment