Skip to content

Instantly share code, notes, and snippets.

@kvadrakot
Last active January 13, 2021 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kvadrakot/bd48b9ef3b46d814594367d0add81d71 to your computer and use it in GitHub Desktop.
Save kvadrakot/bd48b9ef3b46d814594367d0add81d71 to your computer and use it in GitHub Desktop.
HomeFragment
package com.engineer.ui.home
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import androidx.preference.PreferenceManager
import com.engineer.R
import com.engineer.helper.Calc
import com.engineer.helper.GetWay
import com.engineer.helper.ResultFormater
import com.engineer.helper.Utils
import com.engineer.ui.getDatabase
import com.google.android.material.button.MaterialButtonToggleGroup
import com.google.android.material.snackbar.Snackbar
import com.yandex.mobile.ads.AdRequest
import com.yandex.mobile.ads.AdSize
import com.yandex.mobile.ads.AdView
import java.text.SimpleDateFormat
class HomeFragment : Fragment() {
private val RETROFIT_UPDATE_INTERVAL = 300000L
private val TIME_UPDATE_INTERVAL = 15000L
private val updateRetrofitHandler = Handler(Looper.getMainLooper())
private val updateTimeHandler = Handler(Looper.getMainLooper())
private lateinit var homeViewModel: HomeViewModel
private val formatter = SimpleDateFormat("dd/MM/yyyy HH:mm")
private var data:String? = null
private var datatime:String = ""
private var lastupdate:Long = 0
private lateinit var t_eur_buy:TextView
private lateinit var t_usd_sale:TextView
private lateinit var t_usd_buy:TextView
private lateinit var t_eur_sale:TextView
private lateinit var t_rub_buy:TextView
private lateinit var t_rub_sale:TextView
private lateinit var t_eur_sign:TextView
private lateinit var t_usd_sign:TextView
private lateinit var t_rub_sign:TextView
private lateinit var t_timer:TextView
private lateinit var mAdView: AdView
private val blockId = "R-M-DEMO-300x250"
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val database = getDatabase(requireContext())
val repository = TitleRepository(getNetworkService(), database.titleDao)
val root = inflater.inflate(R.layout.fragment_home, container, false)
//Yandex реклама
mAdView = root.findViewById(R.id.banner_view);
mAdView.setBlockId(blockId);
mAdView.setAdSize(AdSize.BANNER_320x50);
val adRequest = AdRequest.Builder().build()
mAdView.loadAd(adRequest);
// val textView: TextView = root.findViewById(R.id.text_home)
// val btn:Button = root.findViewById(R.id.button)
val progressBar:ProgressBar = root.findViewById(R.id.progressBar)
t_timer = root.findViewById(R.id.text_timer)
t_eur_buy = root.findViewById(R.id.eur_buy)
t_usd_sale = root.findViewById(R.id.usd_sale)
t_usd_buy= root.findViewById(R.id.usd_buy)
t_eur_sale = root.findViewById(R.id.eur_sale)
t_rub_buy = root.findViewById(R.id.rub_buy)
t_rub_sale = root.findViewById(R.id.rub_sale)
t_usd_sign = root.findViewById(R.id.textView4)
t_eur_sign = root.findViewById(R.id.textView5)
t_rub_sign = root.findViewById(R.id.textView6)
val input:EditText = root.findViewById(R.id.editText3)
val t_result:TextView = root.findViewById(R.id.textView)
val toggle_group: MaterialButtonToggleGroup = root.findViewById(R.id.toggleGroup)
val toggle_group2: MaterialButtonToggleGroup = root.findViewById(R.id.toggleGroup2)
val toggle_group3: MaterialButtonToggleGroup = root.findViewById(R.id.toggleGroup3)
homeViewModel = ViewModelProvider(this, HomeViewModel.FACTORY(repository)).get(HomeViewModel::class.java)
homeViewModel.title.observe(viewLifecycleOwner, Observer {
data = it
if (it != null) {
datatime = it
}
if (it != null) {
lastupdate = System.currentTimeMillis()
val itemList = Utils.CurrencyFromIT(it)
t_usd_buy.text = itemList.get(0).buy.substring(range = 0..4)
t_usd_sale.text = itemList.get(0).sale.substring(range = 0..4)
t_eur_buy.text = itemList.get(1).buy.substring(range = 0..4)
t_eur_sale.text = itemList.get(1).sale.substring(range = 0..4)
t_rub_buy.text = itemList.get(2).buy.substring(range = 0..3)
t_rub_sale.text = itemList.get(2).sale.substring(range = 0..3)
t_timer.text =
Utils.GetHumanTime(Utils.TimestampFromIT(it) - 1000) + " " + formatter.format(
Utils.TimestampFromIT(
it
)
).toString()
//Обновляем виджит
Intent().also { intent ->
intent.action = "android.appwidget.action.APPWIDGET_UPDATE"
this.requireContext().sendBroadcast(intent)
}
//
// if ( Utils.isTimestampExpire(Utils.TimestampFromIT(it))){
//
// }
}
})
// btn.setOnClickListener { v-> homeViewModel.refreshTitle() }
// btn.setOnClickListener { v->
// Intent().also { intent -> intent.setAction("android.appwidget.action.APPWIDGET_UPDATE")
// requireContext().sendBroadcast(intent)
// }
//
// }
//binding.button.setOnClickListener { v-> Snackbar.make(binding.root, "3432432", Snackbar.LENGTH_SHORT).show() }
//Загружаем настройки
setupPreferencess()
homeViewModel.spinner.observe(viewLifecycleOwner) { value ->
value.let { show ->
progressBar.visibility = if (show) View.VISIBLE else View.GONE
}
}
homeViewModel.snackbar.observe(viewLifecycleOwner) { text ->
text?.let {
Snackbar.make(root, text, Snackbar.LENGTH_SHORT).show()
homeViewModel.onSnackbarShown()
}
}
//Средний ряд
toggle_group.addOnButtonCheckedListener { group, checkedId, isChecked ->
if (isChecked) {
val f = this.resources.getResourceEntryName(checkedId)
val t = this.resources.getResourceEntryName(toggle_group2.checkedButtonId)
val s = this.resources.getResourceEntryName(toggle_group3.checkedButtonId)
val way = GetWay.getWay(f, t, s)
if (input.text != null && !input.text.isEmpty()) {
val count = Calc.getCalc(
way,
Utils.CurrencyFromIT(data),
input.text.toString().toDouble()
)
val res = ResultFormater.set2Format(requireContext(), count!!)
t_result.setText(res)
}
}
}
//Нижний ряд
toggle_group2.addOnButtonCheckedListener { group, checkedId, isChecked ->
if (isChecked) {
val f = this.resources.getResourceEntryName(toggle_group.checkedButtonId)
val t = this.resources.getResourceEntryName(checkedId)
val s = this.resources.getResourceEntryName(toggle_group3.checkedButtonId)
val way = GetWay.getWay(f, t, s)
if (input.text != null && !input.text.isEmpty()) {
val count = Calc.getCalc(
way,
Utils.CurrencyFromIT(data),
input.text.toString().toDouble()
)
val res = ResultFormater.set2Format(requireContext(), count!!)
t_result.setText(res)
}
}
}
//Верхний ряд
toggle_group3.addOnButtonCheckedListener { group, checkedId, isChecked ->
if (isChecked) {
val f = this.resources.getResourceEntryName(toggle_group.checkedButtonId)
val t = this.resources.getResourceEntryName(toggle_group2.checkedButtonId)
val s = this.resources.getResourceEntryName(checkedId)
val way = GetWay.getWay(f, t, s)
if (input.text != null && !input.text.isEmpty()) {
val count = Calc.getCalc(
way,
Utils.CurrencyFromIT(data),
input.text.toString().toDouble()
)
val res = ResultFormater.set2Format(requireContext(), count!!)
t_result.setText(res)
}
}
}
//Textedit изменился
input.addTextChangedListener(
object : TextWatcher {
//Вычисление результата после ввода текста
override fun afterTextChanged(s: Editable?) {
if (s.toString().length > 0 && !s.toString().isNullOrBlank()) {
val f =
context?.resources?.getResourceEntryName(toggle_group.checkedButtonId)
.toString()
val t =
context?.resources?.getResourceEntryName(toggle_group2.checkedButtonId)
.toString()
val s2 =
context?.resources?.getResourceEntryName(toggle_group3.checkedButtonId)
.toString()
val way = GetWay.getWay(f, t, s2)
val count = Calc.getCalc(
way,
Utils.CurrencyFromIT(data),
input.text.toString().toDouble()
)
val res = ResultFormater.set2Format(requireContext(), count!!)
t_result.setText(res)
//Сохраняем ввод для будующих поколений
// val spref = PreferenceManager.getDefaultSharedPreferences(context)
// spref.edit().putFloat("nal_input", binding!!.editText3.text.toString().toFloat()).apply()
}
}
override fun beforeTextChanged(
s: CharSequence?,
start: Int,
count: Int,
after: Int
) {
}
//Проверки на некорректный ввод
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val pattern = Regex("^\\.")
val pattern0 = Regex("^0[0-9]")
if (s != null) {
//Очистка пустого ввода
if (s.toString().length == 0) {
t_result.text = ""
}
//Подстановка нуля
if (pattern.containsMatchIn(s.toString()) && s.toString().length > 1) {
input.setText("0".plus(s.toString()))
input.setSelection(s.toString().length + 1)
}
//Проверка на первую точку
if (s.toString().equals(".")) {
input.setText("0".plus(s.toString()))
input.setSelection(s.toString().length + 1)
}
//Заменяем ноль вначале строки
if (s.toString().length == 2 && pattern0.containsMatchIn(s.toString())) {
input.setText(StringBuilder(s.toString()).insert(1, "."))
input.setSelection(s.toString().length + 1)
}
}
}
}
)
//Реклама
return root
}
public var updateDataRunnable: Runnable = Runnable()
{
run {
homeViewModel.refreshTitle()
//Обновление виджета
Intent().also { intent -> intent.setAction("android.appwidget.action.APPWIDGET_UPDATE")
requireContext().sendBroadcast(intent)}
updateRetrofitHandler.postDelayed(updateDataRunnable, RETROFIT_UPDATE_INTERVAL)
}
}
public var updateTimeRunnable: Runnable = Runnable()
{
run {
t_timer.text = Utils.GetHumanTime(Utils.TimestampFromIT(datatime) - 1000)+" " + formatter.format(
Utils.TimestampFromIT(
datatime
)
).toString()
updateTimeHandler.postDelayed(updateTimeRunnable, TIME_UPDATE_INTERVAL)
}
}
override fun onPause() {
super.onPause()
updateRetrofitHandler.removeCallbacks(updateDataRunnable)
updateTimeHandler.removeCallbacks(updateTimeRunnable)
}
override fun onStart() {
super.onStart()
// Log.v("http", "RUNNABLE")
updateDataRunnable.run()
updateTimeRunnable.run()
}
override fun onResume() {
super.onResume()
t_timer.text = Utils.GetHumanTime(Utils.TimestampFromIT(datatime) - 1000)+" " + formatter.format(
Utils.TimestampFromIT(
datatime
)
).toString()
}
override fun onDestroy() {
super.onDestroy()
}
private fun setupPreferencess() {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val usd_switch = sharedPreferences.getBoolean("usd_switch", false)
val eur_switch = sharedPreferences.getBoolean("eur_switch", false)
val rub_switch = sharedPreferences.getBoolean("rub_switch", false)
if (usd_switch) {
t_usd_sign.setVisibility(View.VISIBLE)
t_usd_buy.setVisibility(View.VISIBLE)
t_usd_sale.setVisibility(View.VISIBLE)
}
if (!usd_switch) {
t_usd_sign.setVisibility(View.GONE)
t_usd_buy.setVisibility(View.GONE)
t_usd_sale.setVisibility(View.GONE)
}
if (eur_switch) {
t_eur_sign.setVisibility(View.VISIBLE)
t_eur_buy.setVisibility(View.VISIBLE)
t_eur_sale.setVisibility(View.VISIBLE)
}
if (!eur_switch) {
t_eur_buy.setVisibility(View.GONE)
t_eur_sign.setVisibility(View.GONE)
t_eur_sale.setVisibility(View.GONE)
}
if (rub_switch) {
t_rub_buy.setVisibility(View.VISIBLE)
t_rub_sign.setVisibility(View.VISIBLE)
t_rub_sale.setVisibility(View.VISIBLE)
}
if (!rub_switch) {
t_rub_buy.setVisibility(View.GONE)
t_rub_sign.setVisibility(View.GONE)
t_rub_sale.setVisibility(View.GONE)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment