没有MainActivity,没有自定义布局的Kotlin对话框/警报

时间:2018-12-27 04:01:45

标签: android kotlin alert alertdialog android-alertdialog

在检查并尝试实施至少8种不同的建议解决方案以在android studio 3.2.1中显示消息框/对话框/警报后,我注意到我无法找到以下任一建议的解决方案:

  1. 在没有显示主消息和/或没有按钮的情况下进行工作。
  2. 补充了如何导入所需库的信息。
我的8次尝试中有6次目前在这两个点中的任何一个遇到瓶颈。对这些尝试中的每一个进行单独的故障排除并没有得出单一方法的工作案例。因此,我有一个问题:

如何在GateKeeper.kt中显示字符串accountType的值

这总结了我到目前为止的尝试:

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外部显示警报对话框而不修改布局。评论建议通过“服务”来做到这一点。我正在调查。

0 个答案:

没有答案