A button that displays different numbers in succession with one click - android-studio

Is there any possibility for the button to display 2 different numbers in a time interval in android studio?
I mean click -> number1 -> 1 sec delay -> number2;
button = (Button)findViewById(R.id.button);
button.setOnClickListener(v -> {
button.setText("number1");
//1sec delay
button.setText("number2");
});

Try running a coroutine something like -
button = (Button)findViewById(R.id.button);
button.setOnClickListener(v -> {
var n = 0
lifecycleScope.launch {
while(n++ < 10) {
buyBtn.text = "number$n"
delay(1000)
}
}
});

Related

Android Studio Kotlin show next textview integer

Im trying to create a generator, when i click the start button, the textview gives me a a random number.
This works great,
but i want to show the numbers still i click stop
so it must give me every few secons a new random number from my mutable List.
How could I do this?
My first opinion was, recursive function.
private fun run() {
var x = 0
var randomListe = mutableListOf<Int>()
randomListe.add(Random.nextInt())
x++
for (element in randomListe) {
var x = 0
val zahlInListe = randomListe[x]
// Thread.sleep(1_000)
// I tried while here
textView.text = ("${randomListe[x]} \n das ist die Random Zahl moruk\n")
}
}
You can launch a coroutine block in lifecycleScope for this and you can also remove redundant x for keeping the current index to show the last value, you can use the last method of ArrayList to get the last value in the list
Make changes to your run method and return a Job object from it so you can cancel it later when the user taps on the stop button.
private fun run(): Job {
return lifecycleScope.launch {
while(true){
delay(1000)
var randomListe = mutableListOf<Int>()
randomListe.add(Random.nextInt())
textView.text = ("${randomListe.last()} \n das ist die Random Zahl moruk\n")
}
}
}
Now keep the return job value in a variable, on calling the run method
private var job: Job? = null
job = run()
Call cancel on job when the user taps on the stop button
btnStop.setOnClickListener{
job?.cancel()
}

AndroidStudio kotlin AlertDialogue with spinner populated with setItems

I want to show a modal dialogue for the user to select a Bluetooth device in the case that I can't guess it from the device names.
It appears that AlertDialogue has the facility to show a spinner / dropdown.
The alert dialogue builder has a method setItems which I seem to think is what I need, however, its parameter is CharSequence[] but I have some sort of array of strings (I can't tell exactly what I have because everything is just val).
private fun showDialog() {
val names = (bta!!.bondedDevices).map { z -> z.name };
// What is the type of names? How can you find this out?
// How can you make it into a CharSequence[]?
val ab = AlertDialog.Builder(this);
ab.setTitle("Select device");
ab.setIcon(android.R.drawable.ic_dialog_alert); // I'd prefer a question mark.
ab.setPositiveButton("Select"){dialogueInterface, which -> Toast.makeText(applicationContext, "Selected", Toast.LENGTH_LONG).show()};
ab.setNeutralButton("Cancel"){dialogueInterface, which -> Toast.makeText(applicationContext, "Cancelled", Toast.LENGTH_LONG).show()};
ab.setItems(names); // None of the following functions can be called with the arguments supplied.
val a = ab.create();
a.setCancelable(false);
a.show();
}
I think this works in Java, but it doesn't in kotlin
CharSequence[] cs = list.toArray(new CharSequence[list.size()]);
So:
In AndroidStudio how can you tell the type of a variable? (In VisualStudio if you hover over a var then the tooltip tells you.)
How in kotlin do you make a CharSequence[]?
fun elmFind() {
// Find device
val pairedDevices: Set<BluetoothDevice>? = bta!!.bondedDevices
// Try to guess.
for (device in pairedDevices!!) {
if (device.name.contains("obd")) {
elmConnect(device.name);
return;
}
}
// Still going therefore didn't find one therefore ask.
val cs: Array<CharSequence> = pairedDevices.map { z -> z.name }.toTypedArray()
var elmDeviceName: String = ""
val ab = AlertDialog.Builder(this);
ab.setTitle("Select device");
ab.setIcon(android.R.drawable.ic_dialog_alert);
ab.setPositiveButton("Select") { dialogueInterface, which ->
elmConnect(elmDeviceName);
};
ab.setNeutralButton("Cancel") { dialogueInterface, which ->
Toast.makeText(
applicationContext,
"Cancelled",
Toast.LENGTH_LONG
).show()
};
ab.setItems(cs) { dialog, which -> elmDeviceName = cs[which].toString() };
val a = ab.create();
a.setCancelable(false);
a.show();
}
Will this work with the local variable elmDeviceName being used to get the value of the selected item in the case when the OK button is pressed?

How to define multiple sharedPreferences?

I have managed to get the sharedPreferences saving values. But i don't know how to make it reference the text i am clicking on. In the // Close Alert Window section when i click ok to change the text. Ok dismisses alert dialog, then suppose to add the new price to list in sharedPreferences.
In the putString() if i use putString("Price$it", input.text.toString()).applyit doesn't appear to do anything. However if i use "Price1" any text i change is saved and upon reopening the app Price1is changed to the new price. So i know the method is working. i just have no clue how to save the particular text i am editing. I hope this makes sense. Thanks for your time.
// Created Private Price List
val sharedPreferences = getSharedPreferences("priceList", Context.MODE_PRIVATE)
//Price
(1..912).forEach {
val id = resources.getIdentifier("Price$it", "id", packageName)
val tv = findViewById<TextView>(id)
tv.text = sharedPreferences.getString("Price$it","0.00")
}
(1..912).forEach {
val id = resources.getIdentifier("Price$it", "id", packageName)
val tv = findViewById<TextView>(id)
tv.setOnLongClickListener {
//Alert Window
val alertDialog = AlertDialog.Builder(this#MainActivity).create()
alertDialog.setTitle("NEW PRICE")
val input = EditText(this#MainActivity)
//Alert Submit on Enter
input.setOnKeyListener { v, keyCode, event ->
if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
// Input changes text
tv.text = input.text
when {
tv.text.startsWith("-") -> tv.setTextColor(Color.RED)
tv.text.startsWith("+") -> tv.setTextColor(Color.GREEN)
else -> {
tv.text = "_"
tv.setTextColor(Color.DKGRAY)
}
}
// Close Alert Window
alertDialog.dismiss()
// TODO Save Price Table //THIS PART vvv
sharedPreferences.edit().putString("Price1", input.text.toString()).apply()
}
false
}
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
input.layoutParams = lp
alertDialog.setView(input)
alertDialog.show()
return#setOnLongClickListener true
}
}
You are shadowing it. In your scope you are referencing the argument of tv.setOnLongClickListener. Specify the argument name so it's not shadowed by inner lambdas.
(1..912).forEach { index ->
...
sharedPreferences.edit().putString("Price$index", input.text.toString()).apply()
}

NSTimer won't trigger function in object

I am making a simple game, and every second, I need the player to lose a food "point". Currently, I have the declaration like so.
var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: player, selector: Selector(player.foodLoss()), userInfo: nil, repeats: true)
And I never hear from the timer again, it has, to the best of my knowledge, no effect on the rest of the app. My Player class is as follows
class Player: Character {
var food = 100
init(startingHealth: Int = 100, startingFood: Int = 100) {
super.init(imageNamed: "Player", entityName: "Player")
food = startingFood
sprite = SKSpriteNode(imageNamed: "Player")
}
func adjustFood(amountToAdjustBy adjustAmount: Int) -> Bool{
if food + adjustAmount <= 100 {
food += adjustAmount
return true
} else {
return false
}
}
func foodLoss() {
food -= 1
print("food lost")
}
}
I get no error when running the code. The only thing that happens is player.food is completely unaffected. Any help with my problem would be very helpful.
Thanks in advance!
You need to change the selector. Right now you would actually call the method foodLoss when creating the timer and use the return value (Void) as the method the timer should call all the time. It therefore will not do anything.
To fix that you need to provide a different selector. For example use Selector("foodLoss") instead:
var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: player, selector: Selector("foodLoss"), userInfo: nil, repeats: true)
To make that work you might have to mark the foodLoss function as #objc:
#objc func foodLoss() {
food -= 1
print("food lost")
}

How to make it two seconds for Time.time?

var targetscript : Diamond;
var red : Color;
var orange : Color;
function Start () {
gameObject.camera.backgroundColor = red;
}
function Update () {
if (targetscript.score > 4) {
gameObject.camera.backgroundColor = Color.Lerp(red, orange, Time.time);
}
}
So right now, if the score is larger than 4 then it would change the camera background color to orange with lerp. But its too quick. I read on the internet that Time.time is 1 second. What is the alternative way but for 2 or 3 seconds? I tried this : http://answers.unity3d.com/questions/328891/controlling-duration-of-colorlerp-in-seconds.html I tried the code for the voted answer but it didn't work. It still lerps through quickly. Does anyone have any ideas? Thanks
Time.time gives you the time in seconds since the start of the game. What you want is Time.deltaTime which is the time difference between each frames.
var targetscript : Diamond;
var red : Color;
var orange : Color;
var t : float = 0;
var duration : float = 3.0; //however long you want it to be
function Start () {
gameObject.camera.backgroundColor = red;
}
function Update () {
if (targetscript.score > 4) {
gameObject.camera.backgroundColor = Color.Lerp(red, orange, t);
t += Time.deltaTime/duration;
}
}
Color.Lerp(Color a, Color b, float t), so:
-> t = 0, the Color result is a
-> t = 0.5, the Color result is half a and half b
-> t = 1.0, the Color result is b
Based on that definition, when Time.time return value >= 1.0 the Lerp will be completed. That's why your code finish in 1 seconds.
so, you can change the update function like this:
var duration : float = 3.0; //however long you want it to be
function Update ()
{
if (targetscript.score > 4)
{
gameObject.camera.backgroundColor = Color.Lerp(red, orange, Time.time / duration);
}
}
This will make the Lerp completes exactly as the duration. because Time.time / duration >= 1 when Time.time >= duration.

Resources