Kotlin диалог / предупреждение без MainActivity, без пользовательского макета - PullRequest
0 голосов
/ 27 декабря 2018

После проверки и попытки реализовать по крайней мере 8 различных предлагаемых решений для отображения окна сообщений / диалогового окна / оповещения в Android Studio 3.2.1, я заметил, что не смог найти ни одного предлагаемого решения, которое бы:

  1. Работает без основной активности и / или без кнопки, которая нажимается перед отображением сообщения.
  2. В дополнение к тому, как импортировать необходимые библиотеки.

6 из 8 моих попыток в настоящее время ограничены в любом из этих двух пунктов.Индивидуальное устранение неисправностей каждой из этих попыток не привело к рабочему случаю для одного подхода.Поэтому у меня есть вопрос:

Как можно отобразить значение строки accountType в GateKeeper.kt ?

Это обобщает мои попытки такдалеко:

package com.greyblocks.gatekeeper

import android.accounts.Account
import android.accounts.AccountManager
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import java.io.File
import java.io.PrintWriter

import com.google.android.material.snackbar.Snackbar
//import android.support.design
//import com.greyblocks.gatekeepersample.MainActivity
import android.widget.AdapterView
import android.content.ContextWrapper
import android.widget.EditText


import android.util.Log
import com.google.android.material.R.id.title
import com.greyblocks.gatekeeper.R.id.info


@Suppress("unused")
open class GateKeeper(private val accountManager: AccountManager,
                      private val accountType: String) {

    fun getCurrentAccount(): Account? {

        val accounts = accountManager.getAccountsByType(accountType)
        if (accounts.isNotEmpty()) {
            return accounts[0]
        }
        return null
    }



    fun getAuthToken(): String? {
        val account = getCurrentAccount()
        return account?.let { accountManager.peekAuthToken(getCurrentAccount(), AccountAuthenticator.AUTHTOKEN_TYPE_FULL_ACCESS) }
    }


    fun enter(user: String, password: String?, authToken: String, userData: Bundle? = null) {
        if (getCurrentAccount() != null) {
            logout()
        }
        accountManager.addAccountExplicitly(Account(user, accountType), password, userData)
        accountManager.setAuthToken(getCurrentAccount(), AccountAuthenticator.AUTHTOKEN_TYPE_FULL_ACCESS, authToken)
    }

    fun saveUserData(key: String, value: Long) {
        accountManager.setUserData(getCurrentAccount(), key, value.toString())
    }

    fun saveUserData(key: String, value: Int) {
        accountManager.setUserData(getCurrentAccount(), key, value.toString())
    }

    fun saveUserData(key: String, value: String) {
        accountManager.setUserData(getCurrentAccount(), key, value)
    }

    fun getUserData(key: String, defaultData: String? = null): String? {
        return accountManager.getUserData(getCurrentAccount(), key) ?: defaultData
    }

    fun getLong(key: String): Long {
        return accountManager.getUserData(getCurrentAccount(), key)?.toLongOrNull() ?: 0L
    }

    fun getInt(key: String): Int {
        return accountManager.getUserData(getCurrentAccount(), key)?.toIntOrNull() ?: 0
    }

    fun logout() {

        //try to write something to screen:
        print("Maximum of a or b is " );
        Log.d("TAG", "message")
        println("other message")

        //info("London is the capital of Great Britain")
//        debug(5) // .toString() method will be executed
//        warn(null) // "null" will be printed
//        toast("Hello, ${name.text}!")
        fun print(message: Any?) {}
        var message:String
        message="D";
        fun print(message: String) {}


        //try to write something to file:
        //writeToTxt(accountType); Crashes upon pressing logout

        if (getCurrentAccount() != null) {


            accountManager.invalidateAuthToken(accountType, getAuthToken())
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
                accountManager.removeAccountExplicitly(getCurrentAccount())
            } else {
                @Suppress("DEPRECATION")
                accountManager.removeAccount(getCurrentAccount(), null, null)
            }
        }

    }

    @Suppress("MemberVisibilityCanBePrivate")
    fun isLoggedIn(): Boolean {
        return getAuthToken() != null
    }

    fun checkUserAuth(activity: Activity) {
        if (!isLoggedIn()) {
            accountManager.addAccount(accountType, AccountAuthenticator.AUTHTOKEN_TYPE_FULL_ACCESS, null, null, activity,
                    null, null)
            activity.finish()
        }
    }

    //Attempt 0: Can't find an import for alert
//    fun messageBox(String inputString){
//        alert("Testing alerts") {
//            title = "Alert"
//            yesButton { toast("Yess!!!") }
//            noButton { }
//        }.show()
//    }

    //Attempt 1: Problem: needs to be called from an object "this" which does not exist in this file.
//    fun showNormalAlert(v: View){
//        val dialog = AlertDialog.Builder(this).setTitle("Kotlin Study").setMessage("Alert Dialog")
//                .setPositiveButton("Confirm", { dialog, i ->
//                    val applicationContext=null;
//                    Toast.makeText(applicationContext, "Hello Friends", Toast.LENGTH_LONG).show()
//                })
//                .setNegativeButton("Cancel", { dialog, i -> })
//        dialog.show()
//    }

    //Attempt 2: Can't find somefile.txt
//    fun writeToTxt(input: String) {
//        File("somefile.txt").printWriter().use { out ->
//            out.println("${input}, ${"text1"}")
//
//        }
//    }

    //Attempt 3: can't find file.txt
    fun writeToTxt(input: String) {
        PrintWriter("file.txt").use {
            for (i in 1..5) {
                println(i)
            }
        }
    }
        //Attempt 4: Do not know yet how to create a parentview in the middle of this code
//    fun writeToTxt(input: String) {
//        Snackbar.make(parentView, "The string = ", Snackbar.LENGTH_LONG).show()
//    }

        //Attempt 5: Don't yet know how to import the design
//    fun onSNACK(view: View){
//        //Snackbar(view)
//        val snackbar = Snackbar.make(view, "Replace with your own action",
//                Snackbar.LENGTH_LONG).setAction("Action", null)
//        snackbar.setActionTextColor(Color.BLUE)
//        val snackbarView = snackbar.view
//        snackbarView.setBackgroundColor(Color.LTGRAY)
//        val textView =
//                snackbarView.findViewById(android.support.design.R.id.snackbar_text) as TextView
//        textView.setTextColor(Color.BLUE)
//        textView.textSize = 28f
//        snackbar.show()
//    }


        //Attempt 6: Don't yet know how to generate the AdapterView<*>
//    fun showPopup(parent: AdapterView<*>, view: View,
//                    position: Int, rowId: Long) {
//        val result: String;
//        val context = ContextWrapper(null)
//        val dialog = AlertDialog.Builder(ContextWrapper(null)).show()
//        val adb = AlertDialog.Builder(context)
//
//        adb.setTitle("List")
//        adb.setMessage(" selected Item is=" + parent.getItemAtPosition(position))
//        adb.setPositiveButton("Ok", null)
//        adb.show()
//        Snackbar.make(view, "Invalid username or password", Snackbar.LENGTH_LONG).show()
//    }

    //Attempt 7: Crashes App upon opening
//    @Throws(Exception::class)
//    fun shouldSetView() {
//        val context = ContextWrapper(null)
//        val builder = AlertDialog.Builder(context)
//        val view = EditText(context)
//        builder.setView(view)
//
//        val alert = builder.create()
//        //shadowOf(alert).getView()
//        view as View
//    }

    //Attempt 8: Can't import inflate
//        fun showNewNameDialog() {
//            val dialogBuilder = AlertDialog.Builder(this)
//            val inflater = this.layoutInflater
//            val dialogView = inflater.inflate(R.layout.custom_dialog, null)
//            dialogBuilder.setView(dialogView)
//
//            val editText = dialogView.findViewById<View>(R.id.editTextName) as EditText
//
//            dialogBuilder.setTitle("Custom dialog")
//            dialogBuilder.setMessage("Enter Name Below")
//            dialogBuilder.setPositiveButton("Save", { dialog, whichButton ->
//                //do something with edt.getText().toString();
//
//                // Add Name in list
//                nameList.add(editText.text.toString())
//                // Handler code here.
//                val intent = Intent(this, NewKitListActivity::class.java)
//                startActivity(intent);
//
//            })
//            dialogBuilder.setNegativeButton("Cancel", { dialog, whichButton ->
//                //pass
//            })
//            val b = dialogBuilder.create()
//            b.show()
//        }
}

Для полноты: я нашел MainActivity в gatekeepersample/java/com.greyblocks.gatekeepersample/MainActivity.kt.Мне удалось добавить кнопку в макете на gatekeeper/res/layout/activity_main.xml, и внутри этой кнопки я могу отображать диалоговые окна предупреждений.Однако остается вопрос, как отображать диалоговые окна предупреждений за пределами MainActivity без изменения макета.В комментариях предлагалось сделать это через «сервис».Я смотрю на это.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...