Created
November 1, 2018 11:39
-
-
Save yousef96m/a4617f4f5efe6e21c3140e3642c78998 to your computer and use it in GitHub Desktop.
KotlinDialog
This file contains 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
/** | |
* Created by Yousef Nasr on 2018-Oct-11. | |
* Email :you96m@gmail.com | |
*/ | |
@SuppressLint("CheckResult") | |
class FeedBackDialog(context: Context?, var callback: (String?) -> Unit) : AppCompatDialog(context), FeedBackDialogAdapter.ItemClickListener { | |
private val feedBackDao: FeedBackDao? by lazy { FeedBackDao() } | |
private var options = RealmList<Feedback>() | |
private var adapter = FeedBackDialogAdapter(options) | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.feedback_dialog) | |
rvFeedback.adapter = adapter | |
initListeners() | |
srFeedback.setOnRefreshListener(this::getFeedbackOptions) | |
loadOptions() | |
} | |
private fun initListeners() { | |
adapter.setClickListener(this) | |
btnFeedbackDialogConfirm?.setOnClickListener { _ -> | |
val selectedOptions = options.filter { it.checked } | |
if (selectedOptions.isNotEmpty()) { | |
callback.invoke(selectedOptions[0]?.id) | |
dismiss() | |
} else { | |
Toast.makeText(context, "Select an option to confirm", Toast.LENGTH_SHORT).show() | |
} | |
} | |
btnFeedbackDialogDismiss?.setOnClickListener { _ -> | |
callback.invoke(null) | |
dismiss() | |
} | |
} | |
private fun loadOptions() { | |
Realm.getDefaultInstance() | |
.where(Feedback::class.java) | |
.findAll() | |
.asFlowable() | |
.subscribe { | |
options.clear() | |
options.addAll(it) | |
adapter.notifyDataSetChanged() | |
if (options.isEmpty()) | |
getFeedbackOptions() | |
} | |
} | |
private fun getFeedbackOptions() { | |
progressBar.visibility = View.VISIBLE | |
feedBackDao?.feedback() | |
?.observeOn(AndroidSchedulers.mainThread()) | |
?.subscribeOn(Schedulers.io()) | |
?.subscribe({ | |
srFeedback.isRefreshing = false | |
progressBar.visibility = View.GONE | |
Realm.getDefaultInstance() | |
.executeTransaction { realm -> | |
realm.where(Feedback::class.java).findAll().deleteAllFromRealm() | |
realm.copyToRealmOrUpdate(it) | |
} | |
}, { | |
it.cause?.message.isNullOrEmpty() | |
}) | |
} | |
override fun onItemClick(view: View, layoutPosition: Int) { | |
adapter.options.forEach { it.checked = false } | |
adapter.options.get(layoutPosition)?.checked = true | |
btnFeedbackDialogConfirm.isEnabled = true | |
btnFeedbackDialogConfirm.setTextColor(Color.parseColor("#EF882B")) | |
adapter.notifyDataSetChanged() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment