-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBaseFragment.kt
More file actions
82 lines (68 loc) · 2.53 KB
/
BaseFragment.kt
File metadata and controls
82 lines (68 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.example.githubfirebaseissue.base
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.example.githubfirebaseissue.R
import okio.IOException
import retrofit2.HttpException
abstract class BaseFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = inflater.inflate(getLayoutRes(), container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewInitialization(view)
}
fun showToast(message: String) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
protected fun showErrorDialog(message: String, actionText: String) {
val dialog = Dialog(requireContext())
with(dialog) {
requestWindowFeature(Window.FEATURE_NO_TITLE)
setCancelable(false)
setContentView(R.layout.error_layout)
}
val title = dialog.findViewById(R.id.txt_message) as TextView
val action = dialog.findViewById(R.id.txt_action) as TextView
title.text = message
action.text = actionText
action.setOnClickListener {
dialog.dismiss()
activity?.onBackPressed()
}
dialog.show()
}
protected fun handleError(th: Throwable) {
val error = when (th) {
is HttpException -> when (th.code()) {
401 -> getString(R.string.error_unauthorized)
500 -> getString(R.string.error_server)
else -> getString(R.string.error_server)
}
is IOException -> getString(R.string.internet_error)
else -> getString(R.string.error_server)
}
onError(error)
}
/**
* This method is called after view has been created.
* This method should be used to initialize all views that are needed to be created (and recreated after fragment is reattached)
* @param view The root view of the fragment
*/
abstract fun viewInitialization(view: View)
abstract fun getLayoutRes(): Int
abstract fun showLoadingState(loading: Boolean)
abstract fun onError(message: String)
}