Reputation: 79
I need to create one textview array, i'd like to show or hide one image depending position. I'll try to explain it: I've one layout similar this:
1 2 3 4 5
And depending random value show or hide an image in textview 1 or 2, etc...
I can use:
if (a == 4)
{
t4.setBackgroundResource(R.drawable.ficha);
t1.setBackgroundDrawable(null);
t2.setBackgroundDrawable(null);
t3.setBackgroundDrawable(null);
t5.setBackgroundDrawable(null);
}
else if (a==5)
...
..
But i'd like to know, if it's possible to pass the number t(1) using parameters or something similar.
Thanks in advance and sorry about my english.
Upvotes: 2
Views: 1169
Reputation: 13174
Have a look at the following snippet;
/*
* Initializes the textViewArray
* You can call this from onCreate.
*/
private void setViews() {
// Declared at class level as private TextView[] textViewArray = null;
textViewArray = new TextView[3];
textViewArray[0] = (TextView) findViewById(R.id.infoText0);
textViewArray[1] = (TextView) findViewById(R.id.infoText1);
textViewArray[2] = (TextView) findViewById(R.id.infoText2);
// Button to demonstrate the functionality
switchButton = (Button) findViewById(R.id.switchButton);
switchButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(imgIndex >= textViewArray.length) {
imgIndex=0;
}
showTextViewImage(imgIndex++);
}
});
}
/*
* Sets the background image only for the textView specified by index
*/
private void showTextViewImage(int index) {
setTitle("" + index);
// First remove the backgroud images from all textviews
for(TextView textView : textViewArray) {
textView.setBackgroundDrawable(null);
}
// If you are using a common image for all textViews, use this
textViewArray[index].setBackgroundResource(R.drawable.ficha);
// If you are using different image for every textView, then use this.
/*
switch (index) {
case 0:
textViewArray[0].setBackgroundResource(R.drawable.ficha0);
break;
case 1:
textViewArray[1].setBackgroundResource(R.drawable.ficha1);
break;
case 2:
textViewArray[2].setBackgroundResource(R.drawable.ficha2);
break;
...
...
...
}
*/
}
Hope, you got the idea.
Upvotes: 2
Reputation: 4431
Or you can use List<TextView> tvList = new ArrayList<TextView>();
add as many textviews as you like
and this will retrieve a textview and set background from a list depending on your a
value :
((TextView)tvList.get(a)).setBackgroundResource(R.drawable.ficha+a.....);
1st 2nd and so on. you can use Arrays too of course for this purpose.
hope it helps abit
Upvotes: 1
Reputation: 1980
you can create textview array like this...
TextView tv[];
tv = new TextView[5];
and you can use Switch Case to show or hide the image...
Upvotes: 2