I have a few ImageViews, all using the same onClick(). How can I get the ID or R.drawable int from the specific ImageView to open another Image depending on the Image I clicked on?
I imagine you have some image views in your xml layout file:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_content" >
<ImageView
android:id="#+id/image_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/image_drawable_1"
android:onClick="doSomething" />
<ImageView
android:id="#+id/image_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/image_drawable_2"
android:onClick="doSomething" />
<ImageView
android:id="#+id/image_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/image_drawable_3"
android:onClick="doSomething" />
</LinearLayout>
You have to add this method to your Activity:
public void doSomething(View v) {
switch (v.getId()) {
case R.id.image_1:
// You clicked on image 1
// If you need to do something to the ImageView with this particular Id then uncomment the next line.
// ImageView imageView = (ImageView) v;
break;
case R.id.image_2:
// You clicked on image 2
break;
case R.id.image_3:
// You clicked on image 3
break;
}
}
Use getResources().getDrawable
Example:
ImageView myImg = (ImageView) findViewById(R.id.myImg);
myImg.setImageResource = getResources().getDrawable( R.drawable.icon );
I don't think you can get the resource identifier that was used to generate the Drawable for the ImageView, but you can save it as a tag of the ImageView when you set the image programmatically.
imageView.setImageResource(R.drawable.image_resource);
imageView.setTag(R.drawable.image_resource);
You can than later retrieve it like that:
int imageResource = (Integer) imageView.getTag();
I stored the Ids of the images which are shown by clicking the onClick() in an int-array, so I created something like a workaround to deal with that issue.
My onClick() looks like this now:
public void showPictureZoomDialog(View view)
{
int singlePicValue400 = 0;
switch (view.getId())
{
case R.id.picture_imgvw_pic1:
singlePicValue400 = currentPicSite.getPicValues400()[0];
break;
case R.id.picture_imgvw_pic2:
singlePicValue400 = currentPicSite.getPicValues400()[1];
break;
case R.id.picture_imgvw_pic3:
singlePicValue400 = currentPicSite.getPicValues400()[2];
break;
case R.id.picture_imgvw_pic4:
singlePicValue400 = currentPicSite.getPicValues400()[3];
break;
case R.id.picture_imgvw_pic5:
singlePicValue400 = currentPicSite.getPicValues400()[4];
break;
case R.id.picture_imgvw_pic6:
singlePicValue400 = currentPicSite.getPicValues400()[5];
break;
case R.id.picture_imgvw_pic7:
singlePicValue400 = currentPicSite.getPicValues400()[6];
break;
case R.id.picture_imgvw_pic8:
singlePicValue400 = currentPicSite.getPicValues400()[7];
break;
case R.id.picture_imgvw_pic9:
singlePicValue400 = currentPicSite.getPicValues400()[8];
break;
case R.id.picture_imgvw_pic10:
singlePicValue400 = currentPicSite.getPicValues400()[9];
break;
}
Intent intent = new Intent(this, PictureZoomDialog.class);
intent.putExtra("PICID", singlePicValue400);
startActivity(intent);
}
I get the Id of the image I want to display via the Intent:
public class PictureZoomDialog extends Activity {
private ImageView mDialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picture_zoom_dialog);
mDialog = (ImageView)findViewById(R.id.pictureactivity_imgvw_pic1);
mDialog.setClickable(true);
mDialog.setImageResource(getIntent().getIntExtra("PICID",-1));
mDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
Thx a lot guys for getting me in the right direction!
You can use the following to get the current Drawable from the ImageView.
Drawable myDrawable = YourImageView.getDrawable();
Then you can go ahead and use myDrawable where ever you want.
Related
I linked the string array to a variable and the I have a button that will add index by 1 and set the textView to the string-array variable[index] so i can show the list of the item in string array one by one, but when I press the button, nothing happen and ViewPostIme0 and ViewPostIme pointer 1 keep cycling in my logcat
I tried everything and
I already tried to simplify the code to its shortest, but still don't work
Simplify code
int index = 0;
Button btn_message;
btn_message = findViewById(R.id.btn_message);
public void onClick(View v) {
switch (v.getId()) {
case (R.id.btn_message):
//if changes in the same page
index++;
btn_message.setText(String.valueOf(messages[index]));
}
}
Full code
package com.example.project;
import android.content.Intent;
import android.content.res.Resources;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn_message, btn_skip;
String[] messages, personal_name;
ImageView LeftImage, RightImage, BackgroundImage;
String name;
TextView test, txt_round;
int index ;
int character;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Importing values
final Intent intent2 = getIntent();
index = intent2.getIntExtra("index", 0);
Intent intent_name = getIntent();
name = intent_name.getStringExtra("name");
//get string array
personal_name = getResources().getStringArray(R.array.name);
messages = getResources().getStringArray(R.array.text);
//find view by id
btn_message = findViewById(R.id.btn_message);
LeftImage = findViewById(R.id.img_left);
RightImage = findViewById(R.id.img_right);
BackgroundImage = findViewById(R.id.img_Background);
test = findViewById(R.id.txtx_Test);
btn_skip = findViewById(R.id.btn_skip);
txt_round = findViewById(R.id.txt_round);
String testing = String.valueOf(index);
test.setText(testing);
testing = String.valueOf(index);
test.setText(testing);
//set Value to varibles
//if image come to main, use this to change things
switch (index) {
case (200):
//BackgroundImage.setImageResource(R.mipmap.);
btn_message.setText(String.valueOf(messages[index]));
break;
}
/* case (13):
test.setText("success");
btn_message.setText(String.valueOf(messages[index]));
break;
case (20):
test.setText("Success2");
btn_message.setText(String.valueOf(messages[index]));
break;
}*/
//Intent intent = getIntent();
//index = intent.getIntExtra("index", 0);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case (R.id.btn_message):
//if changes in the same page
index++;
String testing = String.valueOf(index);
test.setText(testing);
btn_message.setText(String.valueOf(messages[index]));
switch (index) {
//CHANGING POINT ZONE
case (8):
index = 10;
//BackgroundImage.setImageResource(R.mipmap.bg1);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
txt_round.setText(name);
break;
case (16):
index = 20;
BackgroundImage.setImageResource(R.mipmap.bg2);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
txt_round.setText(name);
break;
case (31):
index = 40;
//BackgroundImage.setImageResource(R.mipmap.bg3);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
txt_round.setText("");
break;
case (52):
index = 60;
BackgroundImage.setImageResource(R.mipmap.bg4);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
txt_round.setText("");
break;
case (66):
index = 70;
//BackgroundImage.setImageResource(R.mipmap.cg2);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
txt_round.setText(name);
break;
case (82):
index = 90;
//BackgroundImage.setImageResource(R.mipmap.bg5);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
txt_round.setText("");
break;
case (172):
index = 180;
txt_round.setText(name);
BackgroundImage.setImageResource(R.mipmap.bg6);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
break;
case (183):
index = 190;
txt_round.setText(name);
//BackgroundImage.setImageResource(R.mipmap.cg3);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
break;
//END A END A END A
case (114):
index = 120;
txt_round.setText("");
//BackgroundImage.setImageResource(R.mipmap.bg10);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
break;
case (126):
index = 130;
//BackgroundImage.setImageResource(R.mipmap.bg11);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
txt_round.setText(name);
break;
//END A END A END A
case (145):
//index = 90;
txt_round.setText("");
//BackgroundImage.setImageResource(R.mipmap.endA);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
break;
//END A END A END A
//END B END B END B
case (211):
index = 220;
txt_round.setText(name);
//BackgroundImage.setImageResource(R.mipmap.bg6);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
break;
case (224):
index = 230;
txt_round.setText(name);
//BackgroundImage.setImageResource(R.mipmap.bg4);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
break;
case (234):
index = 240;
txt_round.setText(name);
//BackgroundImage.setImageResource(R.mipmap.cg6);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
break;
//END B END B END B
case (251):
//index = 240;
txt_round.setText(name);
//BackgroundImage.setImageResource(R.mipmap.cg6);
BackgroundImage.setScaleType(ImageView.ScaleType.FIT_XY);
break;
//END B END B END B
//CHOICE AREA
case (105):
AlertDialog.Builder choice_box = new AlertDialog.Builder(MainActivity.this);
View choice_view = getLayoutInflater().inflate(R.layout.activity_choices, null);
Button choice1 = choice_view.findViewById(R.id.choice1);
Button choice2 = choice_view.findViewById(R.id.choice2);
choice_box.setView(choice_view);
AlertDialog dialog = choice_box.create();
dialog.setCanceledOnTouchOutside(false);
final AlertDialog finalDialog3 = dialog;
choice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index = 110;
btn_message.setText(String.valueOf(messages[index]));
txt_round.setText("");
finalDialog3.dismiss();
}
});
//if in screen choice, use this to change in different paths
final AlertDialog finalDialog2 = dialog;
choice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index = 150;
//need to set the index 20's value as instant refresting is not working
btn_message.setText(String.valueOf(messages[index]));
txt_round.setText("");
finalDialog2.dismiss();
}
});
dialog.show();
Window window = dialog.getWindow();
window.setLayout(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
break;
case (203):
choice_box = new AlertDialog.Builder(MainActivity.this);
choice_view = getLayoutInflater().inflate(R.layout.activity_choices, null);
choice1 = choice_view.findViewById(R.id.choice1);
choice2 = choice_view.findViewById(R.id.choice2);
dialog = choice_box.create();
final AlertDialog finalDialog = dialog;
choice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index = 210;
btn_message.setText(String.valueOf(messages[index]));
txt_round.setText("");
finalDialog.dismiss();
}
});
//if in screen choice, use this to change in different paths
final AlertDialog finalDialog1 = dialog;
choice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index = 260;
//need to set the index 20's value as instant refresting is not working
btn_message.setText(String.valueOf(messages[index]));
txt_round.setText("");
finalDialog1.dismiss();
}
});
dialog.show();
window = dialog.getWindow();
window.setLayout(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
break;
case (264):
choice_box = new AlertDialog.Builder(MainActivity.this);
choice_view = getLayoutInflater().inflate(R.layout.activity_choices, null);
choice1 = choice_view.findViewById(R.id.choice1);
choice2 = choice_view.findViewById(R.id.choice2);
dialog = choice_box.create();
final AlertDialog finalDialog4 = dialog;
choice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index = 210;
btn_message.setText(String.valueOf(messages[index]));
txt_round.setText("");
finalDialog4.dismiss();
}
});
//if in screen choice, use this to change in different paths
final AlertDialog finalDialog5 = dialog;
choice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index = 260;
//need to set the index 20's value as instant refresting is not working
btn_message.setText(String.valueOf(messages[index]));
txt_round.setText("");
finalDialog5.dismiss();
}
});
dialog.show();
window = dialog.getWindow();
window.setLayout(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
break;
//CHARCTER ZONE
case (23):
case (29):
case (41):
case (49):
case (51):
case (78):
case (91):
case (93):
case (103):
case (111):
case (124):
case (134):
case (158):
case (161):
case (166):
case (169): {//girl
txt_round.setText("B");
break;
}
case (63):
case (72):
case (74):
case (152):
case (155):
case (157):
case (160):
case (163):
case (188):
case (171): {//shing
character = 2;
txt_round.setText("A");
break;
}
case (10):
case (20):
case (25):
case (30):
case (70):
case (75):
case (76):
case (79):
case (94):
case (100):
case (104):
case (112):
case (123):
case (130):
case (132):
case (136):
case (139):
case (143):
case (153):
case (159):
case (164):
case (180):
case (191): {//playername
txt_round.setText(name);
break;
}
case (193):
Intent intent = new Intent(this, ImageActivity.class);
intent.putExtra("index", index);
startActivity(intent);
break;
default://noone
character = 0;
txt_round.setText("");
//MINIGAME AREA
//OTHER ZONE (PLAYER NAME SET DIALOG ZONE)
btn_message.setText(String.valueOf(messages[index]));
break;
case R.id.btn_skip:
break;
}
}
}
}
Here is the main .xml file is really needed
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/img_Background"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="fitXY"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:srcCompat="#mipmap/bg_test" />
<ImageView
android:id="#+id/img_right"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="450dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#mipmap/normal" />
<ImageView
android:id="#+id/img_left"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginEnd="450dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#mipmap/normal6" />
<Button
android:id="#+id/btn_message"
android:layout_width="713dp"
android:layout_height="146dp"
android:background="#mipmap/bar_5"
android:gravity="top"
android:lines="5"
android:minLines="2"
android:paddingLeft="80px"
android:paddingTop="50px"
android:text="「......enq7f…….」"
android:textAlignment="viewStart"
android:textSize="26sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/txtx_Test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="TextView"
android:textColor="#color/colorPrimaryDark"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/img_Background"
/>
<TextView
android:id="#+id/txt_round"
android:layout_width="171dp"
android:layout_height="40dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="590dp"
android:background="#mipmap/bar_6"
android:gravity="center"
android:paddingTop="15px"
android:text="\u003F \u003F \u003F"
android:textSize="24sp"
app:layout_constraintBottom_toTopOf="#+id/btn_message"
app:layout_constraintEnd_toEndOf="#+id/img_right"
app:layout_constraintHorizontal_bias="0.012"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/btn_skip"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_marginStart="600dp"
android:layout_marginEnd="12dp"
android:layout_marginBottom="3dp"
android:background="#mipmap/bar_3"
android:text="Skip"
app:layout_constraintBottom_toTopOf="#+id/btn_message"
app:layout_constraintEnd_toEndOf="#+id/img_right"
app:layout_constraintHorizontal_bias="0.012"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
Expected: The messages should be set on the button one by one,
Actual: but nothing happened
The reason is because you miss to set listener to your button.
btn_message.setOnClickListener(this);
As #John Joe mentioned you miss to set listener to your button if you don't need to implement listener add android:onClick="onClick" in your button at xml
<Button
android:id="#+id/btn_message"
android:layout_width="713dp"
android:layout_height="146dp"
android:background="#mipmap/bar_5"
android:gravity="top"
android:lines="5"
android:onClick="onClick"
android:minLines="2"
android:paddingLeft="80px"
android:paddingTop="50px"
android:text="「......enq7f…….」"
android:textAlignment="viewStart"
android:textSize="26sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
I have a basic hangman game, and the buttons to make the guesses are all placed on screen with ImageButtons (I had this working perfectly).
I declare the image button ID's like so:
private static final int[] BUTTON_IDS = {
R.id.imageButtonA, R.id.imageButtonB, R.id.imageButtonC, R.id.imageButtonD, R.id.imageButtonE,
R.id.imageButtonF, R.id.imageButtonG, R.id.imageButtonH, R.id.imageButtonI, R.id.imageButtonJ,
R.id.imageButtonK, R.id.imageButtonL, R.id.imageButtonM, R.id.imageButtonN, R.id.imageButtonO,
R.id.imageButtonP, R.id.imageButtonQ, R.id.imageButtonR, R.id.imageButtonS, R.id.imageButtonT,
R.id.imageButtonU, R.id.imageButtonV, R.id.imageButtonW, R.id.imageButtonX, R.id.imageButtonY, R.id.imageButtonZ
};
private List<ImageButton> buttonLetters = new ArrayList<ImageButton>();
Edited to show solution: I register their OnClick by doing:
for (int id: BUTTON_IDS) {
final ImageButton buttonLettersUsage = (ImageButton)findViewById(id);
if (buttonLetters != null) {
assert buttonLettersUsage != null;
buttonLettersUsage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(HangmanActivity.this, " " + buttonLettersUsage.getId(), Toast.LENGTH_SHORT).show();
switch (buttonLettersUsage.getId()){
case R.id.imageButtonQ:
strGuessed = "Q";
break;
case R.id.imageButtonW:
strGuessed = "W";
break;
case R.id.imageButtonE:
strGuessed = "E";
break;
// ... Repeat for rest of buttons ...
default:
break;
}
btnGuessClicked(theIncorrectGuesses, theWord);
buttonLettersUsage.setVisibility(View.INVISIBLE);
}
});
}
}
The problem is now, I've been working on the app some more since implementing this part, and all the buttonLettersUsage.getId()'s have changed.
My question is:
Will they change at any time?
I've not put any new components onto the activity, why have they changed?
Is there a better way to find out which button has been pressed, and give a different value for strGuessed depending on which has been pressed?
Many thanks.
Don't use the numerical ids in the switch case use it as follows.
switch (buttonLettersUsage.getId()){
case R.id.imageButtonA:
strGuessed = "Q";
break;
case R.id.imageButtonB:
strGuessed = "W";
break;
case R.id.imageButtonC:
strGuessed = "E";
break;
// ... Repeat for rest of buttons ...
default:
break;
}
And also don't implement onClickListener like this, use your Activity to implement View.OnClickListener and then set the listener in loop as
buttonLettersUsage.setOnClickListener(this);
Where this is the context of your activity which implements the OnClickListener
YourActivity implements View.OnClickListener{
then in oncreate(){
//add is buton
View buttonAdd = findViewById(R.id.add);
buttonAdd.setOnClickListener(this);}
then
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
{
}
break;}
I have programmatically added a Linear Layout in Android and added ImageViews to it. I used the following code for the same.
LinearLayout layout = (LinearLayout)findViewById(R.id.linear1);
for(int i=0;i<4;i++)
{
imagev = new ImageView(this);
imagev.setLayoutParams(new android.view.ViewGroup.LayoutParams(300,150));
imagev.setMaxHeight(600);
imagev.setMaxWidth(600);
layout.addView(imagev);
}
If i were to implement this, i would give each of the imageviews a specific tag, and then set the same onClickListener to each imageview. Then in the onClickListener, i would check the tag for the imageview that was clicked and do an action depending on whatever imageview was clicked.
LinearLayout layout = (LinearLayout)findViewById(R.id.linear1);
for(int i=0;i<4;i++)
{
imagev = new ImageView(this);
imagev.setLayoutParams(new android.view.ViewGroup.LayoutParams(300,150));
imagev.setMaxHeight(600);
imagev.setMaxWidth(600);
imagev.setTag(i);
imagev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(Integer.valueOf(v.getTag())) {
case 0: ...
break;
case 1: ...
break;
}
}
layout.addView(imagev);
}
This would avoid having to have 4 different onClickListener, and give you some cleaner code.
You can do something like this:
myClickListener1 = new View.OnClickListener ...
myClickListener2 ...
myClickListener3 ...
myClickListener4 ...
for(int i=0;i<4;i++)
{
imagev = new ImageView(this);
imagev.setLayoutParams(new android.view.ViewGroup.LayoutParams(300,150));
imagev.setMaxHeight(600);
imagev.setMaxWidth(600);
switch(i){
case 0: imagev.setOnClickListener(myClickListener1);
break;
case 1: ...
...
}
layout.addView(imagev);
}
I have one ImageView with src, and I want it to change its src onClick. That's easy, but I want to change it's src back to normal when user clicks the imageview again. How can I make it in java?
EDIT:
I already tried this:
public void act1 (View view) {
ImageView ic1 = (ImageView) findViewById(R.id.id1);
Drawable oldBg = ic1.getBackground();
String oldBgStr = ic1.getBackground().toString();
Drawable ic1light = this.getResources().getDrawable(R.drawable.ic1);
Drawable ic1dark = this.getResources().getDrawable(R.drawable.ic1dark);
ic1.setTag(R.drawable.ic1);
if (oldBg == ic1light){
ic1.setBackground(ic1dark);
}
if (oldBg == ic1dark) {
ic1.setBackground(ic1light);
}
ic1.setImageResource(R.drawable.ic1dark);
}
Here is XML of ImageView and Layout it's in:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:background="#color/red"
>
<ImageView
android:id="#+id/id1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="act1"
android:background="#drawable/ic1"
android:adjustViewBounds="true"/>
Simply set a boolean and toggle it whenever the user clicks on the image. Check the boolean each time and display the appropriate image.
private boolean mClicked = false;
public void act1 (View view) {
if(mClicked) {
ic1.setBackground(ic1dark);
}
else {
ic1.setBackground(ic1light);
}
mClicked = !mClicked;
}
Use a boolean to switch between states of current image set like so:
private boolean currentState = false;
public void act1 (View view) {
ImageView ic1 = (ImageView) findViewById(R.id.id1);
// set current src
Drawable oldBg = ic1.getBackground();
String oldBgStr = ic1.getBackground().toString();
Drawable ic1light = this.getResources().getDrawable(R.drawable.ic1);
Drawable ic1dark = this.getResources().getDrawable(R.drawable.ic1dark);
ic1.setTag(R.drawable.ic1);
// when this is called from click event of anything else
if(currentState){
ic1.setBackground(ic1light);
currentState = true;
return;
}
if(!currentState){
ic1.setBackground(ic1dark);
currentState = false;
return;
}
}
So I have a button in my app and an edittext. When I click the button and write something in the edittext, a textview changes. It all works as it should except for one thing. I have to click on the button twice to make it work (only the first time I open activity). The very first time after I open activity I press the button and nothing happens, after that it works as it should.
I already did my research on this and as far as I know the thing that is causing trouble is focus, but I tried a few things and nothing worked.
Button XML code:
<Button
android:id="#+id/submitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/editText1"
android:layout_alignBottom="#+id/editText1"
android:layout_alignLeft="#+id/checkBox25"
android:text="#string/addMaterial"
android:onClick="submitQuantityButton" >
</Button>
Edittext XML code:
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/spinner1"
android:ems="3"
android:inputType="number"
android:maxLength="3" >
</EditText>
I tried adding android:focusableInTouchMode="false" to button XML, I also tried adding requestFocus to button XML and it still doesn't work. I also removed the requestFocus from edittext and it doesn't work. I'm running out of ideas what else to try.
onClick method:
public void submitQuantityButton (View v){
Button submitButton = (Button)findViewById(R.id.submitButton);
final Spinner sItems = (Spinner)findViewById(R.id.spinner1);
final Context context = this;
final CheckBox cb4 = (CheckBox) findViewById(R.id.checkBox4);
final CheckBox cb5 = (CheckBox) findViewById(R.id.checkBox5);
final CheckBox cb33 = (CheckBox) findViewById(R.id.checkBox33);
final CheckBox cb30 = (CheckBox) findViewById(R.id.checkBox30);
final CheckBox cb6 = (CheckBox) findViewById(R.id.checkBox6);
final CheckBox cb7 = (CheckBox) findViewById(R.id.checkBox7);
final CheckBox cb9 = (CheckBox) findViewById(R.id.checkBox9);
final CheckBox cb10 = (CheckBox) findViewById(R.id.checkBox10);
final CheckBox cb11 = (CheckBox) findViewById(R.id.checkBox11);
final CheckBox cb12 = (CheckBox) findViewById(R.id.checkBox12);
//
final AlertDialog.Builder emptyETextErrorBuilder = new AlertDialog.Builder(context);
emptyETextErrorBuilder.setTitle("Warning");
emptyETextErrorBuilder.setMessage("Please enter a value before pressing this button");
emptyETextErrorBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int position = sItems.getSelectedItemPosition();
EditText quantityEditText = (EditText)findViewById(R.id.editText1);
switch (position){
case 0:
AlertDialog.Builder spinnerErrorBuilder = new AlertDialog.Builder(context);
spinnerErrorBuilder.setTitle("Warning");
spinnerErrorBuilder.setMessage("Please choose an item from the list above and then enter a certain value");
spinnerErrorBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog spinnerError = spinnerErrorBuilder.create();
spinnerError.show();
break;
case 1:
String item1 = quantityEditText.getText().toString();
if (item1.matches(""))
{
AlertDialog emptyETextError = emptyETextErrorBuilder.create();
emptyETextError.show();
}
else
{
cb4.setText("Elaborate Totem (" + item1 + "/250)");
}
break;
case 2:
String item2 = quantityEditText.getText().toString();
if (item2.matches(""))
{
AlertDialog emptyETextError = emptyETextErrorBuilder.create();
emptyETextError.show();
}
else
{
cb5.setText("Pile of Crystalline Dust (" + item2 + "/250)");
}
break;
case 3:
String item3 = quantityEditText.getText().toString();
if (item3.matches(""))
{
AlertDialog emptyETextError = emptyETextErrorBuilder.create();
emptyETextError.show();
}
else
{
cb33.setText("Pile of Crystalline Dust (" + item3 + "/250)");
}
break;
case 4:
String item4 = quantityEditText.getText().toString();
if (item4.matches(""))
{
AlertDialog emptyETextError = emptyETextErrorBuilder.create();
emptyETextError.show();
}
else
{
cb30.setText("Pile of Crystalline Dust (" + item4 + "/250)");
}
break;
case 5:
String item5 = quantityEditText.getText().toString();
if (item5.matches(""))
{
AlertDialog emptyETextError = emptyETextErrorBuilder.create();
emptyETextError.show();
}
else
{
cb6.setText("Powerful Venom Sac (" + item5 + "/250)");
}
break;
case 6:
String item6 = quantityEditText.getText().toString();
if (item6.matches(""))
{
AlertDialog emptyETextError = emptyETextErrorBuilder.create();
emptyETextError.show();
}
else
{
cb7.setText("Vial of Powerful Blood (" + item6 + "/250)");
}
break;
case 7:
String item7 = quantityEditText.getText().toString();
if (item7.matches(""))
{
AlertDialog emptyETextError = emptyETextErrorBuilder.create();
emptyETextError.show();
}
else
{
cb9.setText("Ancient Bone (" + item7 + "/250)");
}
break;
case 8:
String item8 = quantityEditText.getText().toString();
if (item8.matches(""))
{
AlertDialog emptyETextError = emptyETextErrorBuilder.create();
emptyETextError.show();
}
else
{
cb10.setText("Armored Scale (" + item8 + "/250)");
}
break;
case 9:
String item9 = quantityEditText.getText().toString();
if (item9.matches(""))
{
AlertDialog emptyETextError = emptyETextErrorBuilder.create();
emptyETextError.show();
}
else
{
cb11.setText("Vicious Claw (" + item9 + "/250)");
}
break;
case 10:
String item10 = quantityEditText.getText().toString();
if (item10.matches(""))
{
AlertDialog emptyETextError = emptyETextErrorBuilder.create();
emptyETextError.show();
}
else
{
cb12.setText("Vicious Fang (" + item10 + "/250)");
}
break;
}
}
});
}
My problem was the Button XML defining:
android:focusableInTouchMode="true"
Remove this attribute and the button doesn't require being touched twice. It appears as though the first touch is consumed to assign focus on the button and the second then triggers the OnClickListener.
Note that the Button works without issue with the android:focusable="true" attribute.
Okay so I finally figured out what caused the problem, by myself. I can't believe I missed such an obvious issue. The thing that caused problem wasn't focus, but the method itself. In my XML file I called onClick method by android:onClick="onClick" and then I also added a buttonlistener inside the onClick method to java code.
All I did was remove the buttonlistener and there's no more double clicking neccessary! So if anyone has this problem in future simply make sure you don't have an onClick method AND buttonlistener at the same time.
Wrong code:
public void submitQuantityButton (View v){
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
.
.
. //REST OF THE CODE
To make it work I simply deleted the onclick listener, leaving only:
public void submitQuantityButton (View v){
.
.
. //REST OF THE CODE
If you are inflating view to another one, try to set on parent view:
view.setFocusable(false);
worked for me.
Sometime I had it problem when click on btn or txt or edt on the fragment, and realy helps use instead .setOnClickListener() need .setOnTouchListener like this example:
txtClose.setOnTouchListener((v, event) -> {
// do staff...
return false;
});
try this once
UPDATED
override onResume method in your activity
and then clear focus from your edittext and set focus to your main layout
edittext.clearFocus();
layout.requestFocus();
or
button.requestFocus();
if the problem is with virtual keyboard it might help you
in your AndroidManifest.xml file inside your Activity tag put this line
android:windowSoftInputMode="stateHidden"
I had the same problem as the OP. I tried all the focus-related suggestions, but none of them worked every time for me.
I tried removing the NavigationDrawer from my layout, but that didn't work.
Lastly, I tried replacing my CoordinatorLayout with a LinearLayout and now my buttons click first time every time. Could be worth a try.
By adding the following lines :
<Button
android:id="#+id/sauvegarder"
android:text="Sauvegarder"
android:layout_gravity="center"
android:background="#color/colorAccent"
android:layout_margin="#dimen/fontmargin"
style="#style/edit"
android:gravity="center"
android:textColor="#color/colorPrimary"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
/>
in my xml file it works perfectly !
Simply use getText() to get text from EditText
And then set text of TextView using setText().