Last active
April 18, 2020 15:45
-
-
Save pksokolowski/fc0806a06b21e6a30bc725edb1baa078 to your computer and use it in GitHub Desktop.
Android custom view starting point to copy-paste instead of remembering. This is a simple case of a view displaying parameters from xml and offering an onclick functionality.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<resources> | |
<declare-styleable name="IconView"> | |
<attr name="image" format="reference|color" /> | |
<attr name="title" format="string" /> | |
</declare-styleable> | |
</resources> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" | |
xmlns:app="http://schemas.android.com/apk/res-auto" | |
android:orientation="vertical" android:layout_width="wrap_content" | |
android:layout_height="wrap_content"> | |
<ImageView | |
android:id="@+id/iconImageView" | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
app:srcCompat="@mipmap/ic_launcher" /> | |
<TextView | |
android:id="@+id/titleTextView" | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:text="TextView" | |
android:textAlignment="center" | |
android:textStyle="bold" /> | |
</LinearLayout> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.util.AttributeSet | |
import android.widget.LinearLayout | |
import kotlinx.android.synthetic.main.icon_view.view.* | |
class IconView @JvmOverloads constructor( | |
context: Context, | |
attrs: AttributeSet? = null | |
) : LinearLayout(context, attrs) { | |
var onClick: (() -> Unit)? = null | |
init { | |
inflate(context, R.layout.icon_view, this) | |
attrs?.apply() | |
setOnClickListener { onClick?.invoke() } | |
} | |
private fun AttributeSet.apply() { | |
val arr = context.obtainStyledAttributes(this, R.styleable.IconView) | |
titleTextView.text = arr.getString(R.styleable.IconView_title) | |
iconImageView.setImageResource( | |
arr.getResourceId( | |
R.styleable.IconView_image, | |
R.drawable.placeholder_24dp | |
) | |
) | |
arr.recycle() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment