Change ImageView image inside onClick event - android

I have an ImageView working as a button in my program. I need it to be an ImageView since I want just the image to be shown, not the borders.
This button is a lamp, if the data in database says it's visible, the lamp must be "on", when you click the button, it will check the data from bank and change it to "off" if it's on and vice-versa.
So, the change of image will happen inside a onClick event.
Here is my code:
btnVisualizar.setClickable(true);
btnVisualizar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
if (visivelBanco.getText().equals("Y")) {
btnVisualizar.setImageResource(this.getResources().getIdentifier(
"drawable/visible_off", null, this.getPackageName()));
} else {
btnVisualizar.setImageResource(
this.getResources().getIdentifier("drawable/visible_on", null, this.getPackageName()));
}
} catch (Exception e) {
Toast.makeText(
getBaseContext(),
"Falha ao modificar visibilidade do item!",
Toast.LENGTH_SHORT).show();
}
}
});
However the compiler doesn't recognize the method getResources() and getPackageName().
What am I doing wrong?
Any help is appreciatted.

The this in there refers to the onClickListener.
Use [Activity].this instead of this, where [Activity] is the name of the Activity

try
String uri = "drawable/visible_off"
btnVisualizar.setImageResource(EdicaoActivity.this.getResources().getIdentifier(uri, "drawable", EdicaoActivity.this.getPackageName()));

I think you just need to use the R class to obtain the identifier of your drawable. For example:
btnVisualizar.setImageResource(R.drawable.visible_on);
You should not need to go messing about with getResources().

Related

Replacing button with imagebutton

So I am working on some code that a friend has left me (I have very little knowledge on this stuff) and have a question regarding Buttons and ImageButtons;
This code is for an app that requires you to click the 'connect' button to enter into a list of bluetooth devices. Once selected you are returned to the home screen and the button now says 'Disconnect'.
Basically, what I want to do is change it from a text based button to an Image button so that I can have a bluetooth icon (black) and when connected change to a connected bluetooth icon (white).
I have the icons and I understand the basic workings for a typical button however this code is a bit much for me. Any help would be greatly appreciated!
I have attached the initial sample of java for reference. The btnConnectDisconnect is the name of the button that I wish to replace.
// Handler Disconnect & Connect button
btnConnectDisconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBtAdapter.isEnabled()) {
Log.i(TAG, "onClick - BT not enabled yet");
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else if (btnConnectDisconnect.getText().equals("Connect")) {
//Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices
Intent newIntent = new Intent(UartActivity.this, DeviceListActivity.class);
startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
}
else if (btnConnectDisconnect.getText().equals("Disconnect")) {
//unpair
System.out.println("Disconnecting from peripheral");
pDeviceAddress = null;
editor.remove("address");
editor.commit();
System.out.println("Currently saved address: " + prefs.getString("address", null));
System.out.println("Currently saved address check: " + pDeviceAddress);
//disconnect from service
Thread thread = new Thread() {
#Override
public void run() {
try {
sleep(50);
mService.disconnect();
System.out.println("Disconnecting from service...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
if(mService == null){
System.out.println("Service disconnected!");
} else System.out.println("Service connected!");
Based on the code, I can see that the button's name is btnConnectDisconnect. So what you can do is go into the XML file where this button is put and first replace the button tag (<Button .../>) with <ImageButton..../>. You can then add android:src="#drawable/name_of_drawable", to the ImageButton tag, to set the image you want the ImageButton to have. Then go back into the code and change the type of btnConnectDisconnect from Button to ImageButton. This should get you to where you want to go without having to touch the code inside the OnClickListener.
Hope this helps!
To get your desired behavior, there are a few things you need to do.
Change the type from Button to ImageButton in your Java file (posted above)
Create a new XML file (btn_bluetooth.xml) in the res/drawable directory with the following contents, making sure you replace the image references:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:drawable="#drawable/BLUETOOTH_CONNECTED_IMAGE_REFERENCE"
/>
<item
android:state_selected="false"
android:drawable="#drawable/BLUETOOTH_DISCONNECTED_IMAGE_REFERENCE""
/>
</selector>
Change the type from Button to ImageButton in your XML layout file (usually referenced in the onCreate or onCreateView method of your Java file (posted above)
When you establish or lose a bluetooth connection, simply call btnConnectDisconnect.setEnabled() with true or false

Check if is it empty on edit text is not working

What i have is android app , and in one of activities i have two edit text with button, and i want either if one of them were empty when i click the button to preform a toast to tell the user to enter data, and if it was not empty i want it to open intent and do other thing , here is my code :
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(quantity.getText()==null){
Toast.makeText(FullImageActivity2.this,"please enter quantity",Toast.LENGTH_LONG).show();
}
else if(extra.getText()==null){
Toast.makeText(FullImageActivity2.this,"please enter extra",Toast.LENGTH_LONG).show();
}
else{
Quan=quantity.getText().toString();
name=itemId;
image=R.drawable.products;
Intent cart=new Intent(FullImageActivity2.this,CartList.class);
cart.putExtra("name", name);
cart.putExtra("quantity",Quan);
cart.putExtra("image", image);
Log.e("quan",Quan+"");
Log.e("name",name+"");
startActivity(cart);
}
}
});
But the weird thing that if they were empty , else is working !! which is not logic at all .. the validation on empty text is not empty , Why this is happening?? Help plz
Try to used .equals() method
if(quantity.getText().toString().trim().equals(""))
Try
if(editText.getText().toString().length()<1){
//do something
}
And of course you are mistaking null with "" which means no string but not null.
When Edittext is empty, getText() method returns empty string, not null.
Try:
if(quantity.getText().toString().equals("")){
Of course, if you want to avoid entering only spaces, use
if(quantity.getText().toString().trim().equals("")){

Login not working

I have written the simple code for Login authentication with hardcoded password.my problem is evenif I am entering the correct password my control is going in elese loop
edt=(EditText)findViewById(R.id.edt);
btn=(Button)findViewById(R.id.sub);
s1=edt.getText().toString();
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("mynameeeeee",s1);
if(s1=="123")
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
}
});
Here's the problem :
You are storing a reference of the edit text content at creation time, when the edit text is empty.
You should retrieve the content of the edit text EVERYTIME you want to compare, which is when the button is clicked in your case :
Do the following :
edt=(EditText)findViewById(R.id.edt);
btn=(Button)findViewById(R.id.sub);
btn.setOnClickListener ( new OnClickListener () {
#Override
public void onClick ( View v ) {
Log.d ( "mynameeeeee" , edt.getText().toString() );
if ( edt.getText().toString().equals ( "123" ) )
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
}
});
the string should be compared like:
if(s1.equals("123")) {}
Change your if statement like this
if(s1.equals("123"))
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
When comparing strings always use .equals() function
== Checks whether both the variable are referring to same object. In this case since they are referring to different object so the result of == is false.
use equals() method s1.equals("123") to check the content of the string object.

Using a != statement with an edittext object in java?

Im trying to create a button which when pushed reads the edittext box to
Make sure its not blank
Make sure its not the default text in this case "First Name".
However when the button is pushed it still preforms the action even if the edittext text is First Name or blank. Is there an easier way to do this? Also the toast are not made when the text is First Name or blank.
createp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (fname.getText().toString() != "")
if (fname.getText().toString() != "First Name"){
prefsEditor.putInt("user", 1);
prefsEditor.commit();
}
if (fname.getText().toString() == "")
{
Toast.makeText(createactivity.this, "You need a first name to create a profile!",
Toast.LENGTH_LONG).show();
}
if (fname.getText().toString() == "First Name") {
Toast.makeText(createactivity.this, "You need a first name to create a profile!",
Toast.LENGTH_LONG).show();
}
}});
}
Try this instead:
if (!fname.getText().toString().equals(""))
...
Another example:
if (fname.getText().toString().equals("First Name"))
....

Trying to use Toast message, but get error

I'm trying to use a Toast message inside a listener method, but I get an error saying something like: Toast is not applicable for the argument.. I don't understand this and can't solve this problem without some help? Thanks!
// Button 1
button_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//text_1.setText("New text for first row!"); // Change text
Toast.makeText(this, "You have clicked on number 1", Toast.LENGTH_LONG).show();
if(controlImage_1)
{
image_1.setImageResource(R.drawable.android_1b); // Change image
controlImage_1 = false;
}
else
{
image_1.setImageResource(R.drawable.android_1a); // Change image
controlImage_1 = true;
}
//Toast.makeText(this, "Your download has resumed.", Toast.LENGTH_LONG).show();
}
});
Try it:
Toast.makeText(**YourClassName.this**, "You have clicked on number 1", Toast.LENGTH_LONG).show();
Without * =)
Toast.makeText(this, "You have clicked on number 1", Toast.LENGTH_LONG).show();
Your this in this statement refers to the View.OnClickListener you created. Read more on anonymous inner classes.
Use MyActivity.this instead
You need to pass in the Context of the current Activity as the first argument. You can't just say this in this case because it is not referring to the application context. You can either create a variable in your on create and use that context or just do this...
Toast.makeText([CLASS_NAME].this, "You have clicked on number 1", Toast.LENGTH_LONG).show();
Replace [CLASS_NAME] with the class that is extending Activity
Try getApplicationContext() as first argument for Toast.makeText or MyActivity.this
here in your code , this refers to the View
Also, if button_1 needs to have onclick listener by default and you are using API > 7,its nice to define onclick="myclickfunction" in the layout itself. Cleans up your code and easy to modify...
Because you are using it in the onClick Listener method, you cannot use only this as the first parameter.
Toast.makeText(ClassName.this, "You have clicked on number 1", Toast.LENGTH_LONG).show();
Use your classname.this as the first parameter.

Categories

Resources