Use ViewBinding in sealed class - android

I have a simple android app, which is changing text and color of TextView depends on how much passengers i added. I want to create a sealed class for each state.
Here is the code of the current app:
class MainActivity : AppCompatActivity() {
private var counter = 0
private val maxPassengers = 50
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.seats.text = counter.toString()
binding.minusButton.setOnClickListener {
counter -= 1
checkAndSwitchState(counter)
}
binding.plusButton.setOnClickListener {
counter += 1
checkAndSwitchState(counter)
}
binding.resetButton.setOnClickListener {
counter = 0
it.visibility = View.GONE
checkAndSwitchState(counter)
}
}
private fun checkAndSwitchState(counter: Int) {
if (counter == 0) {
binding.minusButton.isEnabled = false
binding.textView.text = binding.textView.context.getText(R.string.green_text)
binding.textView.setTextColor(Color.parseColor("#00FF00"))
binding.seats.text = counter.toString()
}
if (counter in 1 until maxPassengers) {
binding.minusButton.isEnabled = true
binding.textView.text = "Осталось мест: " + "${maxPassengers - counter}"
binding.textView.setTextColor(Color.parseColor("#0000FF"))
binding.seats.text = counter.toString()
}
if (counter >= maxPassengers) {
binding.resetButton.visibility = View.VISIBLE
binding.textView.text = binding.textView.context.getText(R.string.red_text)
binding.textView.setTextColor(Color.parseColor("#FF0000"))
binding.seats.text = counter.toString()
}
}
}
So the question is how can i use binding outside MainActivity in sealed class

Related

Kotlin, covert timer activity into a fragment, encountering some errors - Type mismatch. Required: Context! Found: fragment

I have a timer activity. That works great. Now i want to convert that timer into a fragment so I can use it inside a tabLayout.
Now I get some errors inside my PrefUtilStartTimerFrag. With all the "context" I get the error:
Type mismatch.
Required:
Context!
Found:
TabStartTimerFragment
First, this is my Timer fragment Kotlin file:
import android.media.MediaPlayer
import android.os.Bundle
import android.os.CountDownTimer
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.fotf.klimaatambitiegame.util.PrefUtilStartTimerFrag
import kotlinx.android.synthetic.main.fragment_tab_start_timer.*
class TabStartTimerFragment : Fragment() {
enum class TimerState {
Stopped, Paused, Running
}
private lateinit var timer: CountDownTimer
private var timerLengthSeconds: Int = 30
private var timerState = TimerState.Stopped
private var secondsRemaining = 0
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab_start_timer, container, false)
}
// val fab_start = findViewById<Button>(R.id.fab_startfrag)
// val fab_pause = findViewById<Button>(R.id.fab_pausefrag)
// val fab_stop = findViewById<Button>(R.id.fab_stopfrag)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
fab_startfrag.setOnClickListener {
startTimer()
timerState = TabStartTimerFragment.TimerState.Running
updateButtons()
}
fab_pausefrag.setOnClickListener {
timer.cancel()
timerState = TabStartTimerFragment.TimerState.Paused
updateButtons()
}
fab_stopfrag.setOnClickListener {
timer.cancel()
onTimerFinished()
updateButtons()
}
}
override fun onResume() {
super.onResume()
initTimer()
}
override fun onPause() {
super.onPause()
if (timerState == TabStartTimerFragment.TimerState.Running) {
timer.cancel()
} else if (timerState == TabStartTimerFragment.TimerState.Paused) {
}
PrefUtilStartTimerFrag.setPreviousTimerLengthSeconds(timerLengthSeconds, this)
PrefUtilStartTimerFrag.setSecondsRemaining(secondsRemaining, this)
PrefUtilStartTimerFrag.setTimerState(timerState, this)
}
fun initTimer() {
timerState = PrefUtilStartTimerFrag.getTimerState(this)
if (timerState == TabStartTimerFragment.TimerState.Stopped)
setNewTimerLength()
else
setPreviousTimerLength()
secondsRemaining = if (timerState == TabStartTimerFragment.TimerState.Running || timerState == TabStartTimerFragment.TimerState.Paused)
PrefUtilStartTimerFrag.getSecondsRemaining(this).toInt()
else
timerLengthSeconds
if (timerState == TabStartTimerFragment.TimerState.Running)
startTimer()
updateButtons()
updateCountdownUI()
}
private fun onTimerFinished() {
//var progress_countdown = findViewById<ProgressBar>(R.id.progress_countdown)
timerState = TabStartTimerFragment.TimerState.Stopped
setNewTimerLength()
progress_countdown.progress = 0
PrefUtilStartTimerFrag.setSecondsRemaining(timerLengthSeconds, this)
secondsRemaining = timerLengthSeconds
updateButtons()
updateCountdownUI()
}
private fun startTimer() {
var mp = MediaPlayer.create(context, R.raw.elephant)
timerState = TabStartTimerFragment.TimerState.Running
timer = object : CountDownTimer((secondsRemaining * 1000).toLong(), 1000) {
override fun onFinish() {
onTimerFinished()
mp.start()
}
override fun onTick(millisUntilFinished: Long) {
secondsRemaining = (millisUntilFinished / 1000).toInt()
updateCountdownUI()
}
}.start()
}
private fun setNewTimerLength() {
//var progress_countdown = findViewById<ProgressBar>(R.id.progress_countdown)
var lengthInMinutes = PrefUtilStartTimerFrag.getTimerLength(this)
timerLengthSeconds = ((lengthInMinutes * 60L).toInt())
progress_countdown.max = timerLengthSeconds.toInt()
}
private fun setPreviousTimerLength() {
//var progress_countdown = findViewById<ProgressBar>(R.id.progress_countdown)
timerLengthSeconds = PrefUtilStartTimerFrag.getPreviousTimerLengthSeconds(this).toInt()
progress_countdown.max = timerLengthSeconds.toInt()
}
private fun updateCountdownUI() {
//var progress_countdown = findViewById<ProgressBar>(R.id.progress_countdown)
// val textView_Countdown = findViewById<TextView>(R.id.timer_textview)
val minutesUntilFinished = secondsRemaining / 60
val secondsInMinutesUntilFinished = secondsRemaining - minutesUntilFinished * 60
val secondsStr = secondsInMinutesUntilFinished.toString()
timer_textviewfrag.text = "$minutesUntilFinished:${
if (secondsStr.length == 2) secondsStr
else "0" + secondsStr}"
progress_countdown.progress = (timerLengthSeconds - secondsRemaining).toInt()
}
private fun updateButtons() {
//val fab_start = findViewById<Button>(R.id.fab_start)
//val fab_pause = findViewById<Button>(R.id.fab_pause)
//val fab_stop = findViewById<Button>(R.id.fab_stop)
when (timerState) {
TabStartTimerFragment.TimerState.Running -> {
fab_startfrag.isEnabled = false
fab_pausefrag.isEnabled = true
fab_stopfrag.isEnabled = true
}
TabStartTimerFragment.TimerState.Stopped -> {
fab_startfrag.isEnabled = true
fab_pausefrag.isEnabled = false
fab_stopfrag.isEnabled = false
}
TabStartTimerFragment.TimerState.Paused -> {
fab_startfrag.isEnabled = true
fab_pausefrag.isEnabled = false
fab_stopfrag.isEnabled = true
}
}
}
}
Then, this is my PrefUtilStartTimerFrag file:
import android.content.Context
import android.preference.PreferenceManager
import com.fotf.klimaatambitiegame.StadKaartActivity
import com.fotf.klimaatambitiegame.TabStartTimerFragment
class PrefUtilStartTimerFrag {
companion object {
fun getTimerLength(context: TabStartTimerFragment): Double {
//placeholder
return 0.5
}
//private var defValue: Long
private const val PREVIOUS_TIMER_LENGTH_SECONDS_ID = "com.resoconder.timer.previous_timer_length"
fun getPreviousTimerLengthSeconds(context: TabStartTimerFragment): Long {
val preferences = PreferenceManager.getDefaultSharedPreferences(context) //<- Error Type mismatch. Required: Context!
return preferences.getLong(PREVIOUS_TIMER_LENGTH_SECONDS_ID, 0)
}
fun setPreviousTimerLengthSeconds(seconds: Int, context: TabStartTimerFragment) {
val editor = PreferenceManager.getDefaultSharedPreferences(context).edit() //<- Error Type mismatch. Required: Context!
editor.putLong(PREVIOUS_TIMER_LENGTH_SECONDS_ID, seconds.toLong())
editor.apply()
}
private const val TIMER_STATE_ID = "com.resocoder.timer.timer_state"
fun getTimerState(context: TabStartTimerFragment): TabStartTimerFragment.TimerState {
val preferences = PreferenceManager.getDefaultSharedPreferences(context) //<- Error Type mismatch. Required: Context!
val ordinal = preferences.getInt(TIMER_STATE_ID, 0)
return TabStartTimerFragment.TimerState.values()[ordinal]
}
fun setTimerState(state: TabStartTimerFragment.TimerState, context: TabStartTimerFragment) {
val editor = PreferenceManager.getDefaultSharedPreferences(context).edit() //<- Error Type mismatch. Required: Context!
val ordinal = state.ordinal
editor.putInt(TIMER_STATE_ID, ordinal)
editor.apply()
}
private const val SECONDS_REMAINING_ID = "com.resoconder.timer.previous_timer_length"
fun getSecondsRemaining(context: TabStartTimerFragment): Long {
val preferences = PreferenceManager.getDefaultSharedPreferences(context) //<- Error Type mismatch. Required: Context!
return preferences.getLong(SECONDS_REMAINING_ID, 0)
}
fun setSecondsRemaining(seconds: Int, context: TabStartTimerFragment) {
val editor = PreferenceManager.getDefaultSharedPreferences(context).edit() //<- Error Type mismatch. Required: Context!
editor.putLong(SECONDS_REMAINING_ID, seconds.toLong())
editor.apply()
}
}
}
Now how can I fix these errors?

setonclicklistner is not working in kotlin

i am new to kotlin i was trying to make a bmi app from a course i binded the view and every thing is running fine but i think my onclicklistner is not working
below is my code can anyone check and see what is wrong
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
if(binding.weightEditText.text.isNotEmpty() && binding.heightEditText.text.isNotEmpty()) {
binding.calculateButton.setOnClickListener {
val weight = binding.weightEditText.text.toString().toFloat()
val height = binding.heightEditText.text.toString().toFloat()
val myBMI = weight / (height * height)
binding.bmiValue.text = myBMI.toString()
if (myBMI < 18.5) {
binding.imageView.setImageResource(R.drawable.underweight)
} else if (myBMI >= 18.5 && myBMI < 24.9) {
binding.imageView.setImageResource(R.drawable.healthy)
} else if (myBMI >= 24.9 && myBMI < 29.9) {
binding.imageView.setImageResource(R.drawable.overweight)
} else if(myBMI>29.9) {
binding.imageView.setImageResource(R.drawable.obesity)
}
}
}
else{
Toast.makeText(this, "Add the asked field", Toast.LENGTH_SHORT).show()
}
}
}
When your activity is created, your edit text is probably empty. so callback of click not set for your button.
You need to check the editText into the clickListener callback.
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.calculateButton.setOnClickListener {
if(binding.weightEditText.text.isNotEmpty() && binding.heightEditText.text.isNotEmpty()) {
val weight = binding.weightEditText.text.toString().toFloat()
val height = binding.heightEditText.text.toString().toFloat()
val myBMI = weight / (height * height)
binding.bmiValue.text = myBMI.toString()
if (myBMI < 18.5) {
binding.imageView.setImageResource(R.drawable.underweight)
} else if (myBMI >= 18.5 && myBMI < 24.9) {
binding.imageView.setImageResource(R.drawable.healthy)
} else if (myBMI >= 24.9 && myBMI < 29.9) {
binding.imageView.setImageResource(R.drawable.overweight)
} else if(myBMI>29.9) {
binding.imageView.setImageResource(R.drawable.obesity)
}
}else{
Toast.makeText(this, "Add the asked field", Toast.LENGTH_SHORT).show()
}
}
}
}

Toast isn't showing up

Trying to show two Toasts with some info, but one of them isn't showing up.
The points of interest in the code below are functions showScore() and checkAnswer(). The first one doesn't show up its Toast, the second one does. The project builds successfully and the app is working on my phone (Android 9, aarch64).
I just started learning Android. Maybe it's something stupid simple, but I can't get the reason why it's not working.
class MainActivity : AppCompatActivity() {
private lateinit var trueButton: Button
private lateinit var falseButton: Button
private lateinit var nextButton: ImageButton
private lateinit var prevButton: ImageButton
private lateinit var questionTextView: TextView
private val questionBank = listOf(
Question(R.string.question_australia, true),
Question(R.string.question_oceans, true),
Question(R.string.question_mideast, false),
Question(R.string.question_africa, false),
Question(R.string.question_americas, true),
Question(R.string.question_asia, true)
)
private val answers = mutableMapOf<Question, Boolean>()
private var currentIndex = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
trueButton = findViewById(R.id.true_button)
falseButton = findViewById(R.id.false_button)
nextButton = findViewById(R.id.next_button)
prevButton = findViewById(R.id.prev_button)
questionTextView = findViewById(R.id.question_text_view)
trueButton.setOnClickListener { view: View ->
checkAnswer(true)
}
falseButton.setOnClickListener { view: View ->
checkAnswer(false)
}
nextButton.setOnClickListener {
currentIndex = (currentIndex + 1) % questionBank.size
updateQuestion()
checkIfAnswered()
}
prevButton.setOnClickListener {
currentIndex = if (currentIndex > 0) (currentIndex - 1) else (questionBank.size - 1)
updateQuestion()
checkIfAnswered()
}
questionTextView.setOnClickListener {
currentIndex = (currentIndex + 1) % questionBank.size
updateQuestion()
checkIfAnswered()
}
updateQuestion()
}
private fun updateQuestion() {
val questionTextResId = questionBank[currentIndex].textResId
questionTextView.setText(questionTextResId)
}
private fun checkAnswer(userAnswer: Boolean) {
val question = questionBank[currentIndex]
val correctAnswer = question.answer
if (!answers.containsKey(question)) {
answers[question] = userAnswer
falseButton.isEnabled = false
trueButton.isEnabled = false
if (answers.size == questionBank.size) {
showScore()
}
} else {
return
}
val messageResId = if (userAnswer == correctAnswer) {
R.string.correct_toast
} else {
R.string.incorrect_toast
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show()
}
private fun checkIfAnswered() {
if (answers.containsKey(questionBank[currentIndex])) {
falseButton.isEnabled = false
trueButton.isEnabled = false
} else {
falseButton.isEnabled = true
trueButton.isEnabled = true
}
}
private fun showScore() {
var score = 0
answers.forEach {
if (it.key.answer == it.value) {
score += 1
}
}
val toastText = "You answered $score of ${questionBank.size}"
Toast.makeText(this, toastText, Toast.LENGTH_SHORT).show()
}
}
UDP: Tried to run on my friend's phone (Android 9, aarch64) and faced the same issue.
Thanks to one Android-related chat, I found the problem. The problem is that one Toast appears on top of another one. Generally, it's a bad idea to use Toasts this way. If you have a similar problem, consider using Snackbar.

Blank screen with RecyclerView No adapter attached

I'm tying to parse JSON in recyclerview. App compiles fine but it's outputting empty/blank screen
BlogAdapter.kt
class BlogAdapter(private val blogList: List<Blog>) : RecyclerView.Adapter<BlogAdapter.ViewHolder>() {
override fun getItemCount()= blogList.size
private var mContext: Context? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
this.mContext=parent.context;
return ViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.character_item,
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val mBlog = this.blogList[position]
if (mBlog.img != null) {
Glide.with(mContext!!)
.load(mBlog.img)
.into(holder.ivThumbnail)
}
if (mBlog.name != null) {
holder.tvTitle.text = mBlog.name
println("Log: Kabe "+mBlog.name)
}
}
class ViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
val ivThumbnail:ImageView = itemView.findViewById(R.id.ivThumbnail);
val tvTitle:TextView = itemView.findViewById(R.id.tvTitle);
}
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
var mainViewModel: MainViewModel? = null
var mBlogAdapter: BlogAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
getPopularBlog()
swipe_refresh.setOnRefreshListener { getPopularBlog() }
}
private fun getPopularBlog() {
swipe_refresh.isRefreshing = false
mainViewModel!!.allBlog.observe(this, Observer { charactersList ->
prepareRecyclerView(charactersList)
})
}
private fun prepareRecyclerView(blogList: List<Blog>) {
mBlogAdapter = BlogAdapter(blogList)
if (this.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
blogRecyclerView.layoutManager = LinearLayoutManager(this)
} else {
blogRecyclerView.layoutManager = GridLayoutManager(this, 4)
}
blogRecyclerView.itemAnimator = DefaultItemAnimator()
blogRecyclerView.adapter = mBlogAdapter
}
}
My Json file looks like this:
[
{
"id": 1,
"name": "potter",
"img": "https://images.example.com/potter.jpg"
},
{ …}
]
I've created it based on this tutorial: https://itnext.io/kotlin-wrapping-your-head-around-livedata-mutablelivedata-coroutine-networking-and-viewmodel-b552c3a74eec
Any suggestions please
EDIT:
class BlogRepository() {
private var character = mutableListOf<ABCCharacters>()
private var mutableLiveData = MutableLiveData<List<ABCCharacters>>()
val completableJob = Job()
private val coroutineScope = CoroutineScope(Dispatchers.IO + completableJob)
private val thisApiCorService by lazy {
RestApiService.createCorService()
}
fun getMutableLiveData():MutableLiveData<List<ABCCharacters>> {
coroutineScope.launch {
val request = thisApiCorService.getPopularBlog()
withContext(Dispatchers.Main) {
try {
val response = request.await()
val mBlogWrapper = response;
if (/*mBlogWrapper != null &&*/ mBlogWrapper.isNotEmpty()) {
character = mBlogWrapper as MutableList<ABCCharacters>
mutableLiveData.value = character
}
} catch (e: HttpException) {
// Log exception //
} catch (e: Throwable) {
// Log error //)
}
}
}
return mutableLiveData;
}
}
You forget to call notifyDataSetChanged, when you setup your RecyclerView widget. Below the full method call, to make it works.
private fun prepareRecyclerView(blogList: List<Blog>) {
mBlogAdapter = BlogAdapter(blogList)
if (this.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
blogRecyclerView.layoutManager = LinearLayoutManager(this)
} else {
blogRecyclerView.layoutManager = GridLayoutManager(this, 4)
}
blogRecyclerView.itemAnimator = DefaultItemAnimator()
blogRecyclerView.adapter = mBlogAdapter
mBlogAdapter.notifyDataSetChanged()
}
Try using below implementation:
class MainActivity : AppCompatActivity() {
lateinit var mainViewModel: MainViewModel
var mBlogAdapter: BlogAdapter? = null
var blogList: List<Blog> = arrayListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
// init your RV here
prepareRecyclerView()
getPopularBlog()
swipe_refresh.setOnRefreshListener { mainViewModel.getAllBlog() }
}
private fun getPopularBlog() {
swipe_refresh.isRefreshing = false
mainViewModel.getAllBlog().observe(this, Observer { charactersList ->
blogList = charactersList
mBlogAdapter?.notifyDataSetChanged()
})
}
private fun prepareRecyclerView() {
mBlogAdapter = BlogAdapter(blogList)
if (this.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
blogRecyclerView.layoutManager = LinearLayoutManager(this)
} else {
blogRecyclerView.layoutManager = GridLayoutManager(this, 4)
}
blogRecyclerView.itemAnimator = DefaultItemAnimator()
blogRecyclerView.adapter = mBlogAdapter
}
}
Modify your view model like below:
class MainViewModel() : ViewModel() {
val characterRepository= BlogRepository()
fun getAllBlog(): MutableLiveData<List<ABCCharacters>> {
return characterRepository.getMutableLiveData()
}
override fun onCleared() {
super.onCleared()
characterRepository.completableJob.cancel()
}
}

How to implement vertical recyclerview inside another vertical recyclerview

I'm new to android development. I'm developing an app which needs vertical RecyclerView inside another vertical RecyclerView . I created it but the problem is that I want to group the inner RecyclerView elements according to the outer RecyclerView elements.
I have attached the code for reference!
private fun ResponsibilityExpListFun() {
CommonFunctions.hideSoftKeyboard(this#DailyTasksPage)
builder = AlertDialog.Builder(this#DailyTasksPage)
inflater = layoutInflater
dialogView = inflater!!.inflate(R.layout.expandable_list_dialog, null)
dialog = builder!!.create()
expandableListView = dialogView!!.findViewById(R.id.expandablelistview) as ExpandableListView
dialog!!.setView(dialogView)
expandableListView?.setAdapter(TaskResponsibiltyExpandableAdapter(this, expandableListView!!, header, body))
dialog!!.show()
dialog!!.setCancelable(true)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_daily_tasks)
setSupportActionBar(daily_task_toolbar)
daily_task_toolbar.navigationIcon = resources.getDrawable(R.drawable.back_icon)
daily_task_toolbar.setNavigationOnClickListener { finish() }
/* daily_Task_Refresh.setOnRefreshListener {
try {
onStart()
} catch (e: Exception) {
e.printStackTrace()
}
}*/
daily_Task_Refresh.isEnabled = false
val sharedPreferences = getSharedPreferences("App_Details", Context.MODE_PRIVATE)
strMobileIdentifier = sharedPreferences.getString("IMEI_NUMBER", null)
strTokenSecret = sharedPreferences.getString("TOKEN_SECRET", null)
var linearLayoutManager = LinearLayoutManager(this)
Daily_Tasks_recyclerview?.layoutManager = linearLayoutManager
ahowalltaskadapter = AllTaskAdapter(slotIDarrayList)
Daily_Tasks_recyclerview.adapter = ahowalltaskadapter
cayyoverslotadapter = CarryOverSlotAdapter(previousSlotarrayList)
//ahowalltaskadapter = ahowalltaskadapter(slotIDarrayList)
/* preplan_Image_Toggle.setOnClickListener {
preplan_Image_ToggleUp.visibility = View.VISIBLE
preplan_Image_Toggle.visibility = View.GONE
PrePlanTaskRecyclerView.visibility = View.VISIBLE
}
preplan_Image_ToggleUp.setOnClickListener {
preplan_Image_Toggle.visibility = View.VISIBLE
preplan_Image_ToggleUp.visibility = View.GONE
PrePlanTaskRecyclerView.visibility = View.GONE
}*/
fab_btn_DailyTask.setOnClickListener { it ->
builder = AlertDialog.Builder(this)
inflater = layoutInflater
dialogView = inflater!!.inflate(R.layout.edit_curremt_slot, null)
dialog = builder!!.create()
layout = dialogView!!.findViewById(R.id.edit_current_slot_cardview) as CardView
taskName = dialogView!!.findViewById(R.id.edit_content) as TextInputEditText
taskResp = dialogView!!.findViewById(R.id.edit_resp_content) as TextView
taskPackage = dialogView!!.findViewById(R.id.edit_prod_content) as TextView
taskPriority = dialogView!!.findViewById(R.id.edit_priority_content) as TextView
SaveBtn = dialogView!!.findViewById(R.id.SaveEditSlot) as Button
CancelBtn = dialogView!!.findViewById(R.id.cancelEditSlot) as Button
layout!!.setOnClickListener {
CommonFunctions.hideSoftKeyboard(activity = this#DailyTasksPage)
}
CancelBtn!!.setOnClickListener {
dialog!!.dismiss()
}
// expandableListView = dialogView!!.findViewById(R.id.expandablelistview) as ExpandableListView
dialog!!.show()
taskResp!!.setOnClickListener {
count = 1
ResponsibilityExpListFun()
}
taskPackage!!.setOnClickListener {
count = 2
PackageExpListFun()
}
taskPriority!!.setOnClickListener {
PriorityFun()
}
SaveBtn!!.setOnClickListener {
strTaskName = taskName!!.text.toString()
if (strTaskName.isNullOrEmpty()) {
Snackbar.make(dialogView!!, "Task Name field is empty", Snackbar.LENGTH_LONG).show()
return#setOnClickListener
}
if (taskResp!!.text.isNullOrEmpty()) {
Snackbar.make(dialogView!!, "Task Responsibility field is empty", Snackbar.LENGTH_LONG).show()
return#setOnClickListener
}
if (taskPriority!!.text.isNullOrEmpty()) {
Snackbar.make(dialogView!!, "Task Priority field is empty", Snackbar.LENGTH_LONG).show()
return#setOnClickListener
}
AddTaskFunction()
dialog!!.dismiss()
}
// expandableListView?.setAdapter(TaskResponsibiltyExpandableAdapter(this, expandableListView!!, header, body))
dialog!!.setView(dialogView)
dialog!!.show()
// dialog!!.setCancelable(false)
}
}
inner class AllTaskAdapter(val alltaskList: ArrayList<SlotIDClass>) : RecyclerView.Adapter<AllTaskAdapter.ViewHolderAdapter>() {
var slotName: String? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AllTaskAdapter.ViewHolderAdapter {
val View = LayoutInflater.from(parent.context).inflate(R.layout.previous_slot_format, parent, false)
val sharedPreferences = View.context.getSharedPreferences("App_Details", Context.MODE_PRIVATE)
slotName = sharedPreferences.getString("SlotName", null)
return ViewHolderAdapter(View)
}
override fun getItemCount(): Int {
return alltaskList.size
}
override fun onBindViewHolder(holder: AllTaskAdapter.ViewHolderAdapter, position: Int) {
val layoutManager = CustomLinearLayoutManager(holder.itemView.context)
taskinnerAdapter = RunningTaskAdapter(currTaskarrayList)
holder.DailyTasks_Recyclerview!!.setLayoutManager(layoutManager)
holder.DailyTasks_Recyclerview!!.addItemDecoration(DividerItemDecoration(holder.DailyTasks_Recyclerview!!.context, DividerItemDecoration.VERTICAL))
holder.DailyTasks_Recyclerview!!.adapter = taskinnerAdapter
println("Running tASK aDaPtEr------------------------------" + ahowalltaskadapter.toString())
holder.SlotName!!.text = alltaskList.get(position).SlotName
if (holder.SlotName!!.text.equals(slotName)) {
holder.title_prev_slot!!.setBackgroundColor(holder.itemView.resources.getColor(R.color.dark_orange))
holder.strShowime!!.visibility = View.VISIBLE
var SlotTime = (ToMilliseconds!! - CurrentMilliseconds!!).toLong()
object : CountDownTimer(SlotTime.toLong(), 1000) {
override fun onTick(millisUntilFinished: Long) {
strShowime = String.format(Locale.getDefault(), "Time Remaining %02d hour %02d min %02d sec",
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60)
holder.strShowime!!.setText(strShowime)
}
override fun onFinish() {
onStart()
GetCurrentSlot()
}
}.start()
Toast.makeText(holder.itemView.context.applicationContext, strShowime, Toast.LENGTH_LONG).show()
}
}
inner class ViewHolderAdapter(view: View) : RecyclerView.ViewHolder(view), View.OnClickListener {
override fun onClick(v: View?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
var DailyTasks_Recyclerview: RecyclerView? = null
var SlotName: TextView? = null
var title_prev_slot: RelativeLayout? = null
var strShowime: TextView? = null
init {
this.DailyTasks_Recyclerview = view.findViewById(R.id.Daily_Tasks_recyclerview) as RecyclerView
this.SlotName = view.findViewById(R.id.prev_SlotName) as TextView
this.title_prev_slot = view.findViewById(R.id.title_prev_slot) as RelativeLayout
this.strShowime = view.findViewById(R.id.strShowime) as TextView
}
}
}
inner class RunningTaskAdapter(val runningtaskList: ArrayList<TaskDetailsDataClass>) : RecyclerView.Adapter<RunningTaskAdapter.RunningTaskViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RunningTaskAdapter.RunningTaskViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.runningtasks_format, parent, false)
return RunningTaskViewHolder(view)
}
override fun getItemCount(): Int {
return runningtaskList.size
}
override fun onBindViewHolder(holder: RunningTaskAdapter.RunningTaskViewHolder, position: Int) {
holder.tasknameText?.text = runningtaskList.get(position).strTaskName
holder.respnameText?.text = runningtaskList.get(position).strRespName
holder.priorityIDText?.text = runningtaskList.get(position).intPriorityID.toString()
holder.TaskStatusText?.text = runningtaskList.get(position).intTaskStatusID.toString()
holder.PackageText?.text = runningtaskList.get(position).PackageName
holder.intTaskID?.text = runningtaskList.get(position).intTaskID.toString()
holder.intTimeElapsed?.text = runningtaskList.get(position).intTimeElapsed.toString()
holder.intinitial_time_elapsed?.text = runningtaskList.get(position).intinitial_time_elapsed.toString()
holder.strRemarks?.text = runningtaskList.get(position).strRemarks
// holder.ResumeTime?.text = runningtaskList.get(position).ResumeTime
if (holder.TaskStatusText!!.text.equals("1")) {
holder.running_task_Image!!.visibility = View.VISIBLE
} else {
holder.running_task_Image!!.visibility = View.INVISIBLE
}
holder.RunningTaskCardView!!.setOnClickListener {
holder.itemView.context.startActivity(Intent(holder.itemView.context, CurrentTaskDetails::class.java)
.putExtra("Task_Name", holder.tasknameText?.text.toString())
.putExtra("Responsibility_Name", holder.respnameText?.text.toString())
.putExtra("Package_Name", holder.PackageText?.text.toString())
.putExtra("TaskStatusID", holder.TaskStatusText?.text.toString())
.putExtra("Task_ID", holder.intTaskID?.text.toString())
.putExtra("Time_Elapsed", holder.intTimeElapsed?.text.toString())
.putExtra("Initial_Time_Elapsed", holder.intinitial_time_elapsed?.text.toString())
.putExtra("PriorityID", holder.priorityIDText?.text.toString())
.putExtra("Remarks", holder.strRemarks?.text.toString()))
// val activity = holder.itemView.getContext() as AppCompatActivity
// val fragment = CurrentTaskDetails()
// val arguments = Bundle()
// arguments.putString("Task_Name", holder.tasknameText?.text.toString())
// arguments.putString("Responsibility_Name", holder.respnameText?.text.toString())
// fragment.setArguments(arguments)
// activity.supportFragmentManager.beginTransaction().replace(R.id.daily_task_layout, fragment).addToBackStack(null).commit()
}
}
inner class RunningTaskViewHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener {
override fun onClick(v: View?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
var running_task_Image: ImageView? = null
var tasknameText: TextView? = null
var respnameText: TextView? = null
var priorityIDText: TextView? = null
var TaskStatusText: TextView? = null
var RunningTaskCardView: CardView? = null
var PackageText: TextView? = null
var intTaskID: TextView? = null
var intTimeElapsed: TextView? = null
var intinitial_time_elapsed: TextView? = null
var strRemarks: TextView? = null
init {
this.tasknameText = v.findViewById(R.id.task_name_rt_format) as TextView
this.respnameText = v.findViewById(R.id.task_responsibilty_rt_format) as TextView
this.running_task_Image = v.findViewById(R.id.running_task_Image) as ImageView
this.priorityIDText = v.findViewById(R.id.priority_id_rt_format) as TextView
this.TaskStatusText = v.findViewById(R.id.task_status_rt) as TextView
this.PackageText = v.findViewById(R.id.task_package_rt_format) as TextView
this.RunningTaskCardView = v.findViewById(R.id.running_task_cardview) as CardView
this.intTaskID = v.findViewById(R.id.intTaskID) as TextView
this.intTimeElapsed = v.findViewById(R.id.intTimeElapsed) as TextView
this.intinitial_time_elapsed = v.findViewById(R.id.intinitial_time_elapsed) as TextView
this.strRemarks = v.findViewById(R.id.strRemarks) as TextView
}
}
}

Categories

Resources