Skip to content

Instantly share code, notes, and snippets.

@hanihashemi
Created August 24, 2018 01:53
Show Gist options
  • Save hanihashemi/1ac8f5254b5e92fadfba80a9335b53ef to your computer and use it in GitHub Desktop.
Save hanihashemi/1ac8f5254b5e92fadfba80a9335b53ef to your computer and use it in GitHub Desktop.
IconButton for Android
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.annotation.ColorInt
import android.support.v7.widget.LinearLayoutCompat
import android.util.AttributeSet
import android.view.Gravity
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
class IconButton : LinearLayoutCompat {
private var text: String = ""
private var icon: Drawable? = null
private var textView: TextView? = null
private var imageView: ImageView? = null
constructor(context: Context, attrs: AttributeSet? = null) :
super(context, attrs, 0) {
init(attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
super(context, attrs, defStyleAttr) {
init(attrs)
}
private fun init(attrs: AttributeSet?) {
isFocusable = true
isClickable = true
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER
minimumHeight = context.dpToPx(48F)
val typedArray = context.theme
.obtainStyledAttributes(attrs, R.styleable.IconButton, 0, 0)
text = typedArray.getString(R.styleable.IconButton_text) ?: ""
icon = typedArray.getDrawable(R.styleable.IconButton_src)
addImageView()
addTextView()
}
fun setTextColor(@ColorInt color: Int) {
textView?.setTextColor(color)
}
fun setIcon(drawable: Drawable) {
if (imageView == null) {
createImageView(drawable)
return
}
imageView?.setImageDrawable(drawable)
}
private fun addTextView() = addView(createTextView(text))
private fun addImageView() {
if (icon != null)
addView(createImageView(icon!!))
}
private fun createImageView(drawable: Drawable): ImageView? {
imageView = ImageView(context)
imageView?.setImageDrawable(drawable)
return imageView
}
private fun createTextView(text: String): TextView? {
textView = TextView(context)
textView?.text = text
return textView
}
}
//////////////////
////////////////// attrs
//////////////////
<attr name="src" format="reference|color" />
<attr name="text" format="string" />
<declare-styleable name="IconButton">
<attr name="src" />
<attr name="text" />
</declare-styleable>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment