|
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> |