Skip to content

Instantly share code, notes, and snippets.

@nosix
Last active May 26, 2018 02:22
Show Gist options
  • Save nosix/423b1e5a7d6c5837c1e12fab4d7f6bfd to your computer and use it in GitHub Desktop.
Save nosix/423b1e5a7d6c5837c1e12fab4d7f6bfd to your computer and use it in GitHub Desktop.
DialogFragment for Android (SDK 22) in Kotlin 1.0.2
class MainActivity : AppCompatActivity(), SeekDialogFragment.SeekDialogListener {
companion object {
private val TAG = MainActivity::class.qualifiedName;
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val view = findViewById(R.id.button)
view.setOnClickListener {
SeekDialogFragment.show(this, 0, 0..10)
}
// view.setOnTouchListener {
// view, motionEvent ->
// SeekDialogFragment.show(this, 0, 0..10)
// true
// }
}
override fun onChangeSeekValue(value: Int) {
Log.d(TAG, "$value is selected")
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SeekBar
android:id="@+id/seek"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.app.DialogFragment
import android.os.Bundle
import android.widget.SeekBar
class SeekDialogFragment : DialogFragment() {
interface SeekDialogListener {
fun onChangeSeekValue(value: Int)
}
companion object {
val TAG = SeekDialogFragment::class.qualifiedName
val ARG_VALUE = "value"
val ARG_MIN = "min"
val ARG_MAX = "max"
fun show(activity: Activity, value: Int, range: IntRange) {
SeekDialogFragment().apply {
arguments = Bundle().apply {
putInt(ARG_VALUE, value)
putInt(ARG_MIN, range.first)
putInt(ARG_MAX, range.last)
}
}.show(activity.fragmentManager, TAG)
}
}
private var listener: SeekDialogListener? = null
override fun onAttach(activity: Activity) {
super.onAttach(activity)
if (activity is SeekDialogListener) {
listener = activity
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val min = arguments.getInt(ARG_MIN)
val view = activity.layoutInflater.inflate(R.layout.seek_dialog, null)
val seek = view.findViewById(R.id.seek) as SeekBar
seek.run {
max = arguments.getInt(ARG_MAX) - min
progress = arguments.getInt(ARG_VALUE) - min
}
return AlertDialog.Builder(activity)
.setTitle("Seek")
.setView(view)
.setPositiveButton("OK") {
dialog, which ->
listener?.onChangeSeekValue(seek.progress + min)
}
.create()
.apply {
setCanceledOnTouchOutside(false)
}
}
}
@yaosongqwe
Copy link

Why do not use kotlinx.android.synthetic to find seek?
Because that did not work?
I tried that not work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment