Multiple OnClick associated to WebViews inside loop - java

I want to link my Buttons to the associated WebViews. I have 2 lists, one of Button the other one of WebViews. What I'm trying to do is, showing or hiding the webView[x] associated to button[x]
nbObjects = 2;
Button[] buttons = null;
buttons = new Button[nbObjects];
buttons[0] = findViewById(R.id.button0);
buttons[1] = findViewById(R.id.button1);
WeView[] webViews = null;
webViews = new WebView[nbObjects];
webViews[0] = findViewById(R.id.webView0);
webViews[1] = findViewById(R.id.webView1);
for (int i = 0; i < nbObjects; i++) {
webViews[i].setVisibility(View.GONE);
final int j = i;
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (webViews[j].getVisibility() == View.VISIBLE) {
webViews[j].setVisibility(View.GONE);
} else {
webViews[j].setVisibility(View.VISIBLE);
}
}
});
}
Result: when I click on Button0, everything works. WebView0 shows and hides. But not for WebView1 when I click on Button1.
Solution/Update
My WebViews are actually showing up. I added a background color to spot them when no URL was loaded. Now time to loadURL

Related

changing text on textview with button's onClickListener

Hi I'm working at my first bigger app in android studio "FlashCards". I would like it to work so after you click on the button the flashcard's textview changes its text to next random flashcard untill you see all of the them how can i do something like 'continue' to my loop from inside onClick method.
here's the loop's code:
while(i < mTestDeck.size()) {
// generates random number which will represent position in deck.
int random = randomGenerator.nextInt() % mTestDeck.size();
// if random flashcard was already shown create random number again
if (mTestDeck.get(random).wasShown())
continue;
//text view that we will operate on
TextView deckTextView = (TextView) findViewById(R.id.flashcard_text_view);
// set text
deckTextView.setText(mTestDeck.get(random).getFront());
// set mWasShown to true
mTestDeck.get(random).flashcardShown();
Button myButton = (Button) findViewById(R.id.know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mTestDeck.correctAnswer();
}
});
myButton = (Button) findViewById(R.id.dont_know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
First, this way, you have a potential infinite loop. And if it can happens, it will happens! It's not a good idea to "get random item and check if it's ok or try again".
I think that it's better to keep a list with all items in a random order. You just have to iterate over it.
Something like:
int currentPosition = 0;
List<Card> items = new ArrayList<Card>(mTestDeck).shuffle();
// Call this method once in onCreate or anywhere you initialize the UI
private void function setCurrentCard() {
Card currentItem = items.get(currentPosition);
[...] // Set all UI views here
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (currentPosition > items.size) {
// TODO? End?
return;
}
currentPosition++;
setCurrentCard();
}
});
}

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();
}
}

onClick method doesnt work

protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
gl = (GridLayout) findViewById(R.id.grid);
array = new Button[7][6];
Button btn;
for(int i=0; i<7; i++)
{
for(int j=0; j<6; j++)
{
btn = new Button(this);
btn.setId(7*i + j + 1);
array[i][j] = btn;
gl.addView(btn);
}
}
turn = 0;
Toast.makeText(this, "Test", Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v)
{
Toast.makeText(this, "Test1", Toast.LENGTH_SHORT).show();
if(v instanceof Button)
{
Toast.makeText(this, "Test2", Toast.LENGTH_SHORT).show();
int[] d = GetCellByID(v.getId());
Button b = (Button)v;
b.setEnabled(false);
if(turn == 0)
{
b.setBackgroundColor(Color.YELLOW);
turn = 1;
}
else
{
b.setBackgroundColor(Color.RED);
turn = 0;
}
array[d[0]][d[1]] = b;
}
}
This is the code, the Toasts are for testing if what the code is running.
The activity implements OnClickListener
The onClick method does not work, I used it because I have 42 buttons and I can't write 42 setOnClickListener() methods for each button.
In the code I create, in two loop, 42 buttons (7*6) and every time each button is pressed it would be disabled and change the background color of the button one time yellow next time red and again.
You are missing to call the following inside the nested for loop:
btn.setOnClickListener(this);
Here, this refers to Activity which implements OnClickListener
set the onClickListner for your button you have missed that.
for(int i=0; i<7; i++)
{
for(int j=0; j<6; j++)
{
btn = new Button(this);
btn.setId(7*i + j + 1);
array[i][j] = btn;
gl.addView(btn);
btn.setOnClickListener(this);
}
}
From the code snipper you've posted, I don't see anything linking the onClick method to your button(s).
Try adding
btn.setOnClickListener(this);
into the for-loop
Call method in your onCreate()
yourButton.setOnClickListener(this);
You must call method in your onCreate()
Try this :
yourbuttonname.setOnClickListener(this);
or
yourbuttonname.setOnClickListener(yourActivity.this);

Get the Integer behind ImageView Array

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.

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
}
}

Categories