Get the Integer behind ImageView Array - java

I have this thing into my application.
That I want to do is this, when someone presses the die with the number 5 I want to add 5 points into his ArrayList. I was thinking for an Listener but how would I know which ImageView has been pressed?
Currently I am using this method to get the right placeholders in the board
public ImageView[] initiateDice() {
ImageView pDice1 = (ImageView) findViewById(R.id.die_one);
ImageView pDice2 = (ImageView) findViewById(R.id.die_two);
ImageView pDice3 = (ImageView) findViewById(R.id.die_three);
ImageView pDice4 = (ImageView) findViewById(R.id.die_four);
ImageView pDice5 = (ImageView) findViewById(R.id.die_five);
ImageView pDice6 = (ImageView) findViewById(R.id.die_six);
ImageView pDice7 = (ImageView) findViewById(R.id.die_seven);
ImageView pDice8 = (ImageView) findViewById(R.id.die_eight);
ImageView[] placeHolders = new ImageView[] {pDice1, pDice2, pDice3, pDice4, pDice5, pDice6, pDice7, pDice8};
return placeHolders;
}
and I am "printing" the dice on the screen using that method
public void printDice(int[] array1, ImageView[] array2) {
for (int i = 0; i < array1.length; i++) {
array2[i].setImageResource(diceImages[array1[i] - 1]);
array2[i].setVisibility(View.VISIBLE);
}
}
where the first array is 8 random generated numbers for the dice and the second array is the PlaceHolders.
The diceImages is for the images of the dice, the six states of them.
private final int[] diceImages = new int[] {R.drawable.dice_one, R.drawable.dice_two, R.drawable.dice_three,
R.drawable.dice_four, R.drawable.dice_five, R.drawable.dice_pico };
Any thoughts or suggestions are welcome.

Other answers are providing some of the solution, but you're actually asking about how to get the number displayed in the image view, in which case, you can save it to the tag:
public void printDice(int[] array1, ImageView[] array2) {
for (int i = 0; i < array1.length; i++) {
array2[i].setImageResource(diceImages[array1[i] - 1]);
array2[i].setVisibility(View.VISIBLE);
array2[i].setTag(array1[i]);
}
}
And modifying Matt's answer:
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
Integer dieValue = v.getTag();
// do something
}
};
pDice1.setOnClickListnener(listener);
pDice2.setOnClickListnener(listener);
pDice3.setOnClickListnener(listener);
pDice4.setOnClickListnener(listener);
pDice5.setOnClickListnener(listener);
pDice6.setOnClickListnener(listener);
pDice6.setOnClickListnener(listener);
pDice8.setOnClickListnener(listener);

One way to do it is to set an OnClickListener like this:
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
if (v == pDice1) {
// do something
} else if (v == pDice2) {
...
}
}
};
pDice1.setOnClickListnener(listener);
pDice2.setOnClickListnener(listener);
pDice3.setOnClickListnener(listener);
pDice4.setOnClickListnener(listener);
pDice5.setOnClickListnener(listener);
pDice6.setOnClickListnener(listener);
pDice6.setOnClickListnener(listener);
pDice8.setOnClickListnener(listener);

You would set an OnClickListener() to all ImageViews. The OnClickListener() gets passed the View that has clicked. View has a getId() that returns an int with the id of the View. Then it is only a matter of adding either a switch or if(){...} else if(...)() to perform a specific action based on the id of the View that was clicked.

Related

How to get data from many EditTexts when Its added in layout programmatically in android

I'm adding EditText in linear layout and it gives a view like that in image.
I'm getting this view by using this code.
public class SearchRecipe extends AppCompatActivity {
LinearLayout parentLayout;
ImageButton searchRecipe;
private int EDITTEXT_ID = 1;
private List<EditText> editTextList;
EditText editTextItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_recipe);
setActionBar();
init();
searchRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextItem = (EditText) parentLayout.findViewById(EDITTEXT_ID);
for (int i = 0; i < editTextList.size(); i++) {
Log.e("All Values=", editTextList.get(i).getText().toString());
Toast.makeText(SearchRecipe.this, editTextItem.getText().toString() + " ", Toast.LENGTH_SHORT).show();
}
}
});
}
public void init() {
parentLayout = (LinearLayout) findViewById(R.id.parent_layout); //make sure you have set vertical orientation attribute on your xml
searchRecipe = (ImageButton) findViewById(R.id.search_button);
editTextList = new ArrayList<EditText>();
TextView addMoreText = new TextView(this);
addMoreText.setText("Add More Ingredients");
addMoreText.setGravity(Gravity.CENTER);
addMoreText.setPadding(20, 20, 20, 20);
addMoreText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.add, 0);
addMoreText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editTextItem = new EditText(SearchRecipe.this);
editTextItem.setId(EDITTEXT_ID);
editTextList.add(editTextItem);
EDITTEXT_ID++;
editTextItem.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.cross, 0);
editTextItem.setPadding(20, 20, 20, 20);
editTextItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
parentLayout.removeView(editTextItem);
return true;
}
});
parentLayout.addView(editTextItem, 0);
}
});
parentLayout.addView(addMoreText);
}
Now the only problem I'm facing is that. I'm not getting the text from edittext properly. Let me Explain what I want to do.
Click on Add More TextView will add one more edit text.
After adding all edittexts I will click on Search button.
By clicking search button will get the data from edittexs and save in arraylist. I tried a lot but can't do this properly. will you please help me to do this thing ? I'm stuck in from many days.
if you are createing edit text run time only for this purpose then there is no need of below tow lines
editTextItem.setId(EDITTEXT_ID);
EDITTEXT_ID++;
To retrive data from each edit box follow below things
for (EditText editText : editTextList) {
/* now you can get the value from Edit-text and save in the ArrayList
or you can append it in same string*/
yourArraList.add(editText.getText().toString()));
}
Get the editext from your list editTextList
String data = editTextList.get(index).getText().toString();
Add check for editTextList should not be null or empty.
You can iterate over list using for-each loop
for (EditText editText : editTextList) {
// now you can get the value from Edit-text and save in the ArrayList
yourArraList.add(editText.getText().toString()));
}
you can do like below if view inside fragment.
public static String getText(final Activity activity) {
final StringBuilder stringBuilder=new StringBuilder();
LinearLayout scrollViewlinerLayout = (LinearLayout) activity.findViewById(R.id.linearLayoutForm);
ArrayList<String> msg = new ArrayList<String>();
for (int i = 0; i < scrollViewlinerLayout.getChildCount(); i++)
{
LinearLayout innerLayout = (LinearLayout) scrollViewlinerLayout.getChildAt(i);
EditText editText = (EditText) innerLayout.findViewById(R.id.meeting_dialog_et);
msg.add(editText.getText().toString());
}
for (int j=0;j<msg.size();j++)
{
stringBuilder.append(msg.get(j)).append(";");
}
Toast t = Toast.makeText(activity.getApplicationContext(), stringBuilder.toString(), Toast.LENGTH_SHORT);
t.show();
return stringBuilder.toString();
}
there is another way is make arraylist Edittexes and add each edittext when it added to layout. then you can get like below:
for (int i = 0; i < Edittexes.size(); i++) {
if (Edittexes.get(i) == view)
{
String text=Edittexes.get(i).getText();
}
}

How do I randomize images in android studio? The code I wrote isn't working

I want to randomize the the back images that will be brought from a database(code still not added), but the code I wrote isn't working. I have originally just added the flip function. I searched up how to randomize images and tried to follow the code given. Sadly its not working for me.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get references to the imageView objects
imgUpperLeft = (ImageView) findViewById(R.id.imgUpperLeft);
imgUpperRight = (ImageView) findViewById(R.id.imageView2);
imgLowerLeft = (ImageView) findViewById(R.id.imageView3);
imgLowerRight = (ImageView) findViewById(R.id.imageView4);
// Setting the initial image (First face of cards)
imgUpperLeft.setImageResource(R.drawable.img_waterfall);
imgUpperRight.setImageResource(R.drawable.img_waterfall);
imgLowerLeft.setImageResource(R.drawable.img_waterfall);
imgLowerRight.setImageResource(R.drawable.img_waterfall);
imgUpperLeft.setVisibility(View.VISIBLE);
imgUpperRight.setVisibility(View.VISIBLE);
imgLowerLeft.setVisibility(View.VISIBLE);
imgLowerRight.setVisibility(View.VISIBLE);
}
ImageView imgView = new ImageView(this);
Random rand = new Random();
int rndInt = rand.nextInt(4) + 1; // n = the number of images, that start at idx 1
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
// Shows the second face of the cards
public void showUpperLeftImage(View v){
imgView.setImageResource(id);
}
public void showUpperRightImage(View v){
imgView.setImageResource(id);
}
public void showLowerLeftImage(View v){
imgView.setImageResource(id);
}
public void showLowerRightImage(View v){
imgView.setImageResource(id);
}
Two things in your code stand out to me:
ImageView imgView = new ImageView(this);
This ImageView is not part of the view hierarchy, meaning it is not on screen. Was it ever meant to be on screen? If not, then I don't think you need this.
public void showUpperLeftImage(View v){
imgView.setImageResource(id);
}
You have four methods like this one that change the image of the view that is not on screen. Judging by their method names, I think you want to change the image of the four ImageViews you found earlier with findViewById().
I think you want to do this:
public void showUpperLeftImage(int id) {
imgUpperLeft.setImageResource(id);
}
public void showUpperRightImage(int id) {
imgUpperRight.setImageResource(id);
}
public void showLowerLeftImage(int id) {
imgLowerLeft.setImageResource(id);
}
public void showLowerRightImage(int id) {
imgLowerRight.setImageResource(id);
}

How to identify which `view` has been clicked?

Look at following android code. IMGS is a 2 dimensional array of ImageView. I am adding onClickListener to it in a for loop. How to identify which view has been clicked ? I dont want to iterate over all the 36 elements using view.getId();.
private static final Integer[] Icons = {
R.drawable.r,
R.drawable.re,
R.drawable.u,
R.drawable.et,
R.drawable.w,
R.drawable.ya
};
private ImageView[][] IMGS= new ImageView[6][6];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IMGS[0][0] = (ImageView) findViewById(R.id.immg11);
for (int i=0; i < 6; i++)
{
for (int j=0; j<6; j++)
{
Drawable d = getResources().getDrawable(Icons[i]);
IMGS[i][j].setImageDrawable(d);
IMGS[i][j].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//HOW TO KNOW WHICH VIEW HAS BEEN CLICKED ?
}
});
}
}
}
Notice the View argument passed to onClick(View v)? It's the view that was clicked.
You can call v.getId() to retrieve its id.
Agreed, but there are 36 elements over which i have to iterate if I use this method. Is there a way to know the indexes of clicked IMGS ?
You can use setTag() to save whatever data you want in each view and retrieve it later with getTag().

Optimising Android/Java Code - Creating multiple instances of the same object type

I have a working application but want to optimise the code. Below is one example where I create 10 separate imagebuttons (note the incrementing objectname and XML reference for each) and set their listeners. Can anyone suggest a more optimal way of doing this, perhaps in a dynamic method/loop please? Thanks....
private void initialiseButtons() {
ImageButton imageButton1 = (ImageButton)this.findViewById(R.id.imageButton1);
imageButton1.setOnClickListener(this);
ImageButton imageButton2 = (ImageButton)this.findViewById(R.id.imageButton2);
imageButton2.setOnClickListener(this);
ImageButton imageButton3 = (ImageButton)this.findViewById(R.id.imageButton3);
imageButton3.setOnClickListener(this);
ImageButton imageButton4 = (ImageButton)this.findViewById(R.id.imageButton4);
imageButton4.setOnClickListener(this);
ImageButton imageButton5 = (ImageButton)this.findViewById(R.id.imageButton5);
imageButton5.setOnClickListener(this);
ImageButton imageButton6 = (ImageButton)this.findViewById(R.id.imageButton6);
imageButton6.setOnClickListener(this);
ImageButton imageButton7 = (ImageButton)this.findViewById(R.id.imageButton7);
imageButton7.setOnClickListener(this);
ImageButton imageButton8 = (ImageButton)this.findViewById(R.id.imageButton8);
imageButton8.setOnClickListener(this);
ImageButton imageButton9 = (ImageButton)this.findViewById(R.id.imageButton9);
imageButton9.setOnClickListener(this);
ImageButton imageButton0 = (ImageButton)this.findViewById(R.id.imageButton0);
imageButton0.setOnClickListener(this);
}
You could use a loop and use getIdentifier() method.
int idToInitialize;
ImageButton ib;
for (int i = 0; i < 9; i++) {
idToInitialize = getResources().getIdentifier("imageButton" + i, "id", getPackageName());
ib = (ImageButton) this.findViewById(idToInitialize);
ib.setOnClickListener(this);
}
Hovewer, it is very slow if we compare to the normal method.
You can reduce the boilerplate code by using http://androidannotations.org/ which will allow you to do someting like that
#ViewById
ImageButton imageButton1;
but it would be perhaps better to use an array or a list of buttons rather than multiple references, something like that for example :
private void init() {
int[] ids=new int[]{R.id.imageButton1, R.id.imageButton2 ...};
List<ImageButton> buttons=new ArrayList<ImageButton>;
for(int id : ids) {
buttons.add((ImageButton)this.findViewById(id));
}
}
you can then easily iterate on the List, for example to set the listener
for(ImageButton button : buttons) {
button.setOnClickListener(this);
}
You can use arrays, lists ...
For example:
private static final int[] BUTTONS_IDS = new int[] {R.id.imageButton0, R.id.imageButton1, R.id.imageButton2, R.id.imageButton3, R.id.imageButton4, R.id.imageButton5, R.id.imageButton6, R.id.imageButton7, R.id.imageButton8, R.id.imageButton9};
ImageButton[] buttons = new ImageButton[BUTTON_IDS.length];
private void initialiseButtons() {
for (int i = 0; i < BUTTONS_IDS.length; i++) {
buttons[i] = (ImageButton) findViewById(BUTTONS_IDS[i]);
buttons[i].setOnClickListener(this);
}
}
You can also put the list of ids in the arrays.xml file.
I can't try it cause I have no Android Environmetn here. But I think this should work:
private void initialiseButtons() {
for(int i = 0; i < 10; i++) {
ImageButton imageButton = (ImageButton)this.findViewById(R.id.getClass().
getField("imageButton" + i).get(R.id));
imageButton.setOnClickListener(this);
}
}
If it's only for setting the onClickListener, you can get rid off your whole initialiseButtons() methods and simply add android:onClick="handleButtonClick" in your layout xml and define that method in your activity like so:
public void handleButtonClick(View view) {
switch(view.getId()) {
case R.id.imageButton1: // handle button 1 pressed ....
case R.id.imageButton2: // handle button 2 pressed ....
// ... handle further buttons
}
}

Android, How to pass the name of int variable to a popupwindow?

How can I pass the name of an int variable to a popupwindow when an image is clicked? I have set an int per image and I have a lot of images that I had set.
This is how I'm using the int in a textView on a PopupWindow.
public boolean onLongClick(View v) {
// v.setTag(v);
case R.id.hsv1iv1:
ImageView ivpopup = (ImageView) popupView.findViewById(R.id.pv1);
intcount1++; // I would like to pass this int name to the popup window.
break;
case R.id.hsv2iv1:
ImageView ivpopup = (ImageView) popupView.findViewById(R.id.pv1);
intcount2++; // I would like to pass this int name to the popup window.
break;
LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
popupWindow.update(0, 0, 800, 500);
ColorDrawable dw = new ColorDrawable(-005500);
popupWindow.setBackgroundDrawable(dw);
tvpwlikectr = (TextView) popupView.findViewById(R.id.liketv);
Button pwlikebtn = (Button) popupView.findViewById(R.id.pwlikebtn);
Button btnDismiss = (Button)popupView.findViewById(R.id.cancel);
pwlikebtn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
intcount1++;
tvpwlikectr.setText(Integer.toString(intcount1)); // this code doesn't work with the intcount1
}});
btnDismiss.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
popupWindow.dismiss();
popupWindow.setTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
}
}
Could you explain how you are setting the INT per image? Copying and pasting the code on how you set an INT per image would be helpful, because it's unclear what you mean by you are setting an INT per image.
Also, are you interested in the value of the int variable or the name of the variable? Showing how you are settings lots of images with int per image would help clarify what you are trying to do.
-- adding answer after seeing the updated post with code --
I would create an object that has the name you are interested in (i.e. intcount1) and an int to keep the actual value. After that, you can associate each button/ImaveView with that object with the view.setTag method, and get the value via view.getTag method. Here's an example:
private class MyTag {
String mTagName;
int mCount;
MyTag(String tagName) {
mTagName = tagName;
mCount = 0;
}
}
// in your onCreate or initializaion code somewhere
ImageView view1 = (ImageView) popupView.findViewById(R.id.hsv1iv1);
MyTag imageTag = new MyTag("intcount1");
view1.setTag(imageTag);
ImageView view2 = (ImageView) popupView.findViewById(R.id.hsv1iv1);
// this will go wherever you handle the onLongClick
public boolean onLongClick(View v) {
Object tag = v.getTag();
if (tag instanceof MyTag) {
MyTag myTag = (MyTag) tag;
myTag.mCount++;
}
}
// I'm assuming you are setting the text from the actual clicked object
// so this will go wherever you are setting the text/handling the click
public void onClick(View v) {
Object tag = v.getTag();
if (tag instanceof MyTag) {
MyTag myTag = (MyTag) tag;
myTag.mCount++;
tvpwlikectr.setText(myTag.mTagName);
}
}
The bottom line is, creating an object with name/count value, associate each View with its own object using the view.setTag() function, and when you need to read the values, use the view.getTag() to get the object and read the mTagName (the "variable" name) and the mCount (the "variable" value).

Categories