Skip to content

Instantly share code, notes, and snippets.

@karino2
Created February 25, 2017 11:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karino2/461dbd89df909637eaa246ff29d570ab to your computer and use it in GitHub Desktop.
Save karino2/461dbd89df909637eaa246ff29d570ab to your computer and use it in GitHub Desktop.
Androidを支える技術Iのサンプルに作ったカスタムビュー
public class HelloCustomView extends View {
String first;
String second;
public HelloCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.HelloCustomView, 0, 0);
first = a.getString(R.styleable.HelloCustomView_firstText);
second = a.getString(R.styleable.HelloCustomView_secondText);
a.recycle();
every5Secondes();
}
Paint bgpaint = new Paint();
Paint fgpaint = new Paint();
@Override
protected void onDraw(Canvas canvas) {
bgpaint.setStyle(Paint.Style.FILL);
bgpaint.setColor(Color.RED);
canvas.drawRect(0, 0, getWidth(), getHeight(), bgpaint);
fgpaint.setColor(Color.BLACK);
fgpaint.setTextSize(100);
// String text = isAltText ? "Custom" : "Hello";
String text = isAltText ? second : first;
canvas.drawText(text, 10, 100, fgpaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
Toast.makeText(getContext(), "touched!", Toast.LENGTH_LONG).show();
return true;
}
return super.onTouchEvent(event);
}
Handler handler = new Handler();
boolean isAltText = false;
void every5Secondes() {
isAltText = !isAltText;
invalidate();
handler.postDelayed(new Runnable() {
@Override
public void run() {
every5Secondes();
}
}, 5000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment