I'm having a Floating Action Button listener with AlertDiaolog inside. And I want to use my buttons from XML. And if I want to write an onClickListener() for them.
So in Java I have to initialize it like:
butAdd = (Button)dialog.findViewById(R.id.btn_add)
butAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Some code
}
But when I trying to use:
var butAdd = dialog?.findViewById(R.id.btn_add) as Button;
in Kotlin it's incorrect
So any suggestions how to fix it? What'is wrong with listeners?
Here is my code of Floating Action Button:
fab?.setOnClickListener {
diaolg = AlertDialog.Builder(this#Cards)
val linearlayout = getLayoutInflater().inflate(R.layout.add_password, null)
diaolg?.setView(linearlayout)
?.setTitle("Add a new password")
?.setCancelable(true)
var login = findViewById(R.id.login) as EditText
var password = findViewById(R.id.password) as EditText
var title = findViewById(R.id.title) as EditText
var butAdd = diaolg?.findViewById(R.id.btn_add) as Button
var butCancel = diaolg?.findViewById(R.id.btn_cancel) as Button
butAdd.setOnClickListener(View.OnClickListener {
fun onClick(v:View){
}
})
butCancel.setOnClickListener(View.OnClickListener {
fun onClick(v:View){
}
})
diaolg?.create()
diaolg?.show()
}
please find id by using
var butAdd = linearlayout.findViewById<Button>(R.id.btn_add) as Button;
Whatever class you're in has no findViewById method.
You have to findViewById on the inflated layout, so:
var login = linearLayout.findViewById(R.id.login) as EditText
Also, I dont think you need to have the ? on the dialog, it cannot be null.
Also, I would make your views vals instead of vars.
import this line in your Activity
<Button
android:id="#+id/btn_submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="submit" />
import this line in your Activity
// Using R.layout.activity_main from the main source set
//activity_main is your layout file name
import kotlinx.android.synthetic.main.activity_main.*
btn_submit.setOnClickListener {
Toast.makeText(this, "hello", Toast.LENGTH_LONG).show();
}
Its work for me.
Related
I'm a beginner and I want to make an app that combine basic colors depending on user input. For example input 1 = red, and input 2 = yellow, click combine button then the background will change to color orange. (using kotlin)
I have no idea how to do it but here is my progress
package com.example.calculator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var b1=findViewById(R.id.combine) as Button
var e1=findViewById(R.id.color1enter) as EditText
var e2=findViewById(R.id.color2enter) as EditText
b1.setOnClickListener{
if e1 = "red" and e2 = "yellow"{
make background orange
}
}
}
}
input 1 = red
input 2 = yellow
background changes to color orange
If you are wanting to change the background of the app, once you define the colors then you can call the layout background change in the button click.
Example
// set button 1 with its id
button1 = findViewById(R.id.btVar1);
// set button 2 with its id
button2 = findViewById(R.id.btVar2);
// set relative layout with its id
relativeLayout = findViewById(R.id.rlVar1);
// onClick function for button 1
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// set the color to relative layout
relativeLayout.setBackgroundResource(R.color.cool);
}
});
// onClick function for button 2
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// set the color to relative layout
relativeLayout.setBackgroundResource(R.color.warm);
}
});
This is based off two buttons as an example. If you want all of this on one button then you can use if statement in the click event of one button to change the colors on the background.
There is several ways you can achieve this. But this is a great example. To combine the colors you will have set the palette color as well
I'm developing a solution that passes the one activity for other activity after the user clicks in an ImageButton. I have 6 images and all images
are having the same onClick event and I need to distinguish different ImageButton's clicks which is which for passing for the second activity.
I tried the solution below, but the line with idImageButton.tag.toString() doesn't work.
file.kt
fun onclickImage(view: View){
val idImageButton:ImageButton = view as ImageButton
val pokemonName:String = idImageButton.tag.toString()
val myIntent = Intent(this, Details::class.java)
myIntent.putExtra("pokemon", pokemonName)
startActivity(myIntent)
}
You can get view id with casting to ImageButton
when(view.id) {
R.id.btnFirst -> {}
R.id.btnSecond -> {}
//so on
}
val button:ImageButton
val id = button.id
You have to checked the id of the view to distinguish them. For Example if the id of the ImageButton for which you want to move to the second activity is pokemon, then try like this.
fun onclickImage(view: View) {
if(view.id == R.id.pokemon) {
val myIntent = Intent(this, Details::class.java)
myIntent.putExtra("pokemon", "Pokemon")
startActivity(myIntent)
}
}
If you also want to do it by tag you have to set tag in either xml or code. Then you can check it with tag
<ImageButton
android:id="#+id/pokemon"
android:tag="Pokemon"
android:onClick="onclickImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Then check tag and take decision.
fun onclickImage(view: View) {
val pokemonName = view.tag.toString()
if(pokemonName.equals("Pokemon", true)) {
val myIntent = Intent(this, Details::class.java)
myIntent.putExtra("pokemon", pokemonName)
startActivity(myIntent)
}
}
I am trying to set the layout visibility with data binding. While the data is being loaded from the database, the default visibility which I set in XML is not working. Here is the layout file
<RelativeLayout
android:id="#+id/error_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="#{homeViewModel.comfortErrorVisibility, default=invisible}"/>
The view model is like this
public class HomeViewModel extends BaseObservable {
private ObservableField<String> comfortErrorMessage = new ObservableField<>();
public HomeViewModel(){
validateSpace();
}
#Bindable
public int getComfortErrorVisibility(){
// change the visibility based on error message
return TextUtils.isEmpty(comfortErrorMessage.get()) ? View.VISIBLE : View.INVISIBLE;
}
private void validateSpace(){
//some business logic to set the comfrotErrorMessage
}
}
Am I missing anything here? By default, I want to set the visibility as invisible for error layout. But its shown by default.
Afaik, default is just for the preview on Android studio and won't do anything in runtime. Can't find the official documentation anymore, but there are quite a few SO Posts about it.
From what I can tell, when you set the binding the data binding framework will call getComfortErrorVisibility to get the visibility of error message. Your condition is set so that when the error message is empty or null the visibility is visible:
TextUtils.isEmpty(comfortErrorMessage.get()) ? View.VISIBLE : View.INVISIBLE;
Because your comfortErrorMessage is initialized like ObservableField(), its initial value will be null and hence the first thing you see is a visible error field.
Maybe you should change the condition for the visibility?
this is because you make a mistake in getComfortErrorVisibility method. At start your comfortErrorMessage is empty so your method return visible a and text view will be shown, try change your method to:
#Bindable
public int getComfortErrorVisibility(){
return TextUtils.isEmpty(comfortErrorMessage.get()) ? View.INVISIBLE: View.VISIBLE;
}
public class HomeViewModel extends BaseObservable {
private ObservableField<String> comfortErrorMessage = new ObservableField<>();
public HomeViewModel(){
validateSpace();
}
}
import text utils in your <data> binding tag and ...
<RelativeLayout
android:id="#+id/error_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="#{TextUtils.isEmpty(viewmodel.comfortErrorMessage) ? View.VISIBLE : View.INVISIBLE"/>
use visibility = invisible or gone:
<RelativeLayout
android:id="#+id/error_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"/>
and then change the visibilty programmatically where you need it
if(TextUtils.isEmpty(some_error))
{
findViewbyId(R.id.error_layout).setVisibilty(View.VISIBILE)}
}
Add your comfortErrorVisibility , init it as View.INVISIBLE
private ObservableField<String> comfortErrorMessage = new ObservableField<>();
private ObservableField<Integer> comfortErrorVisibility = new ObservableField<>(View.INVISIBLE);
In your XML, just put the field name:
<RelativeLayout
android:id="#+id/error_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="#{homeViewModel.comfortErrorVisibility}"/>
If your comfortErrorMessage can be changed dynamically on runtime i.e. user is able to edit it from an EditText, then u can instead add property changed callback
import android.text.TextUtils;
import android.view.View;
import androidx.databinding.BaseObservable;
import androidx.databinding.Observable;
import androidx.databinding.ObservableField;
public class HomeViewModel extends BaseObservable {
private ObservableField<String> comfortErrorMessage = new ObservableField<>();
private ObservableField<Integer> comfortErrorVisibility = new ObservableField<>(View.INVISIBLE);
public HomeViewModel() {
validateSpace();
comfortErrorMessage.addOnPropertyChangedCallback(
new Observable.OnPropertyChangedCallback() {
#Override
public void onPropertyChanged(Observable sender, int propertyId) {
if (TextUtils.isEmpty(comfortErrorMessage.get())) {
comfortErrorVisibility.set(View.VISIBLE);
} else {
comfortErrorVisibility.set(View.INVISIBLE);
}
}
}
);
}
private void validateSpace() {
//some business logic to set the comfrotErrorMessage
}
}
and your comfortErrorMessage should assigned with two-way binding with = sign "#={homeViewModel.comfortErrorMessage}"
I have common problem with findViewById() function, it returns null:
<EditText
android:id="#+id/nameText"
/>
<Button
android:text="Save"
android:onClick="buttonClick1"
/>
</TableRow
android:onClick="buttonClick1"
/>
Activity1.java:
public class Activity1 extends ActionBarActivity {
public void buttonClick1(View view) {
setContentView(view);
EditText nameText = (EditText) view.findViewById(R.id.nameText);
EditText lastNameText = (EditText) view.findViewById(R.id.lastNameText);
EditText indexNumberText = (EditText) view.findViewById(R.id.indexNumberText);
Log.d(">>>> ", nameText.getText().toString());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity1);
}
}
}
In buttonClick1() findViewById() returns null. Please explain why?
Remove setContentView(view); from buttonClick1 method
and initialise all your textview in this manner by removing view.
EditText nameText = (EditText) findViewById(R.id.nameText);
EditText lastNameText = (EditText) findViewById(R.id.lastNameText);
EditText indexNumberText = (EditText) findViewById(R.id.indexNumberText);
Also initialize the controls in the xml properly by giving height and width to controls
Multiple problems unless you're not posting all your code.
1) In your XML you close a TableRow tag, but I don't see you opening it. Might just be lazy copy-pasting.
2) In your onCreate you seem to be missing a listener for your button. There is nothing to indicate that you have a button anywhere. You need to find the view of your button as follows:
Button button = (Button) findViewById(R.id.nameOfButton);
Then you need to set a listener for it like this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Here goes whatever should happen when you click the button.
}
});
3) As for your ButtonClick1 method, delete it. It looks like you were trying to create a listener, but it is pretty far from what it should look like.
Try to replace your code by this one :
public class Activity1 extends ActionBarActivity {
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity1);
EditText nameText = (EditText) findViewById(R.id.nameText);
EditText lastNameText = (EditText) findViewById(R.id.lastNameText);
EditText indexNumberText = (EditText) findViewById(R.id.indexNumberText);
}
public void buttonClick1(View view) {
//Your stuff
Log.d(">>>> ", nameText.getText().toString());
}
}
Since now would be the normal code that have you tried, if you want to set a click on a button you'll have to declare it as :
Button button1 = (Button) findViewById(R.id.button1);
Then you can do the :
public void buttonClick1(View v) {
// Your stuff
}
EDIT
Make sure that you have on your XML all of your EditText and all of your Button for example : or , also make sure that you have an android:id="#+id/yourID in all of your stuff..., by the way instead of using an onClick method in your XML for your Button, you could use this to use an OnClickListener
The point 1 to 3 should go inside of onCreate the point 4 should go outside of onCreate.
1.- Implements View.OnClickListener in your Activity1
public class Activity1 extends ActionBarActivity implements View.OnClickListener {
2.- Declare it
Button button1 = (Button) findViewById(R.id.button1);
3.- Do the setOnClickListener like this :
button1.setOnClickListener(this);
4.- Create an OnClick method :
#Override
public void onClick(View view) {
if (View.equals(button1))
//Your stuff
}
I'm new in android world and I have a problem, well, I'm making a project very simple it is about an activity where i have a button and an EditText. The button has an event onClick in XML.
My problem is it: I need the button value and send this value to
EditText but my button don't have a id. Help me I don't know how manipulate a element if it dont have a id.
XML Code:
<View
android:layout_height="#dimen/cell_height"
android:background="#color/red"/>
<Button
android:layout_marginLeft="#dimen/button_margin"
android:layout_gravity="center_vertical"
android:text="#string/hex_red"
android:textColor="#color/red"
android:onClick="copy"/>`
Java code:
public void copy(View boton){
EditText txtSelected = (EditText)this.findViewById(R.id.txtColor)
String color = boton; <-- here need the button value
txtSelected.setText(color);
}
I need your help, Thanks
you can say boton.getText().toString()
Modify your copy() function like this:
public void copy(View boton) {
EditText txtSelected = (EditText)this.findViewById(R.id.txtColor)
Button btn = (Button) boton; // << key point.
String color = btn.getText().toString();
txtSelected.setText(color);
}`
public void onClickBtn(View view) {
EditText txtSelected = (EditText)this.findViewById(R.id.txtColor)
Button btn = (Button)(view);
String value = (String) btn.getText();
txtSelected.setText(value);
txtSelected.setSelection(value.length()); // cursor will be at the end of the text
}