Retrieve elements through using variable IDs - android

I have number of check-boxes with their ids as per a pattern sequence.
Like checkboxes1, checkboxes2, checkboxes3 etc..
I want to run a loop keeping each box, retrieve value, perform some function and move on.
Something like:
for(int i=0;i<9;i++)
{
String elementId="checkboxes"+Integer.toString(i);
CheckBox elementcb = (CheckBox) findViewById(R.id.elementId);
}
But of course the above thing won’t work as I can’t just simple append a variable in front of R.id.. So how can I achieve the above?

for(int i=0;i<9;i++)
{
String elementId="checkboxes"+Integer.toString(i);
int resID = getResources().getIdentifier(elementId,"id", getPackageName());
CheckBox elementcb = (CheckBox) findViewById(resID);
}
hope this help :)

Related

Remove items from array with auto generated onclick

I create a vertical list of textviews with an arraylist and attach on onclicklistener to each one. In the onclick I set code to remove that item. When I click in sequence from the last generated to the first this works fine. But if I remove the first one and then the last one it gives me a null pointer exception. I know this is happening because it is attempting to remove an index that is no longer present, or at least that is what I think is happening. But I cannot figure out how to solve that.
private void generateViews(){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
final TextView[] textView = new TextView[questionArray.size()];
for(int i = 0; i < questionArray.size(); i++){
final int Index = i;
textView[Index] = new TextView(getActivity());
textView[Index].setText(questionArray.get(i));
textView[Index].setId(Index);
textView[Index].setGravity(Gravity.CENTER);
textView[Index].setPadding(15,15,15,15);
textView[Index].setLayoutParams(params);
textView[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (textView[Index].getId() == (v).getId()) {
questionArray.remove(Index);
answerArray.remove(Index);
saveVariables();
updateViews();
((ViewGroup) textView[Index].getParent()).removeView(textView[Index]);
Toast.makeText(getActivity(), "Question and Answer removed!", Toast.LENGTH_SHORT).show();
}
}
});
mainLayout.addView(textView[Index]);
}
EDIT:
I figured out a small fix but it has it's problems. Instead of removing the items from the arrays with the index I can remove them by searching for the text within the textview.
The problem with this solve is that if my array contains 2 items that are identical then it may remove the wrong index.
questionText = textView[Index].getText().toString();
answerText = textView[Index].getText().toString();
if(questionArray.contains(questionText) && questionArray.size() > 0){
questionArray.remove(questionText);
answerArray.remove(answerText);
}
Solved:
I solved it by first searching for the index of the question text and removing that index from both arrays. The arrays are user generated and I plan on preventing the user from entering the same question twice.
questionText = textView[Index].getText().toString();
int questionIndex = questionArray.indexOf(questionText);
questionArray.remove(questionIndex);
answerArray.remove(questionIndex);
Also, I did it this way because I am still an amateur and was not aware of the Recyclerview. I plan on educating myself on that function and hopefully implementing it.
I really have no idea about why you want do this? if you just want remove textview in a list , why don't you use listview or recyclerview instead ?
You should consider using RecyclerView.

android findviewbyid() use int at id field

I have a pretty simple question:
int i=0;
n = (TextView) findViewById(R.id. "value of i" );
How can I get this working? I want in the place of id to use my int value, is it possible? if so how do I go about doing this?
I'll put the code:
private void sxhmatismos7(String[][] pinakas)
{
TextView n;
int i=0;
for (i=0;i<12;i++)
{
n = (TextView) findViewById(R.id."HERE VALUE OF i");
if (n.getText().equals(pinakas[0][0]))
{
n.setVisibility(View.VISIBLE);
}
}
}
Something like this should work:
int id = resources.getIdentifier(String.valueOf(i), "id", "com.my.package");
n = (TextView) findViewById(id);
Android docs
There is only one way, you will have to create the TextView Dynamically and add it to your layout, there is a method called:
view.setId(int i);
here you can set the id of your view and can access it.
You don't use it that way. R.id.value is a Resource Id, typically from your layouts.
R.id.value is a public final int from the R.java file. The Id number is generated by your editor and is something like -11222388. There is almost never a time to not use code that looks like (View) findViewById(R.id.itemId);.

How to get dynamic CheckBox Id

I have created checkbox dynamically. Based on the require list size just am creating new dynamic check box in a repeated manner and am also setting the Id for that. Now i want to do check it in other loop.
for(int i=0;i<require.size();i++)
{
//From Requirements
requirement=require.get(i);
RelativeLayout rl1 = new RelativeLayout(getActivity());
rl1.setBackgroundResource(R.drawable.listviewdesign);
l1.setOrientation(LinearLayout.VERTICAL);
req1 = new CheckBox(getActivity());
rl1.addView(req1);
req1.setId(Integer.parseInt(requirement.r_id));
Log.i("getid",Integer.toString(req1.getId()));
li.add(Integer.toString(req1.getId()));
}
In this loop am just checking element of li and proj_require1 values. If both are equal then I want to make the CheckBox as checked. For that i have written the code here.
for(int i=0;i<li.size();i++)
{
//li.get(i);
req1 = (CheckBox) container.findViewById(i);
String sr = req1.toString();
for(int j=0;j<proj_require1.size();j++)
{
pr = proj_require1.get(j);
if(sr.equals(pr.rid))
{
req1.setChecked(!req1.isChecked());
}
else
{
req1.setChecked(req1.isChecked());
}
}
}
But my doubt is in first loop am creating the CheckBox based on the size of require object. So every time it creates the CheckBox inside the loop. But in second loop am trying to access the checkbox which am created in the first loop. Could anyone please help me to solve this problem? The only way is i can create the CheckBox in the first loop. I want to access it in other loop. Is it possible?

Dynamic access to elements of the layout

I have a question that is driving me crazy.
I have a large number of buttons (10, more or less) on my screen, inside a TableRow.
I need to access them, and I had planned to perform through a loop.
Access to one, is very easy, adding this:
boton7 = (Button) findViewById (R.id.Btn7)
My question is, if you can dynamically set the id string (R.id.Btn7) to put in a can get the buttons for, and for example, change the color .... something like this:
for (int i = 0; i <10; i + +) {
Button eachBoton= (Button) findViewById (R.id.Btn + i);
eachBoton. setBackgroundColor (Color.Red);
}
That, of course, does not work .... my question is if anyone knows how exactly the chain can be mounted
R.id.Btn + i
to work.
Thanks a lot.
You can use Resources#getIdentifier() to get a resource identifier for the given resource name:
int resourceId = getResources().getIdentifier(
"Btn"+i,
"id",
this.getContext().getPackageName());
Button button = (Button) findViewById(resourceId);
Alternately you can prepare an array with all the ids you need and access elements of that array. This is more efficient:
private final int[] btns = {R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4, ...}
...
Button button = (Button) findViewById(btns[i]);
Give an identifier to your layout ("layout" in the example below) and then iterate over all the touchable children by using getTouchables. If it's a button, change the color.
View layout = findViewById(R.id.layout)
ArrayList<View> touchables = layout.getTouchables();
for (View b : touchables) {
if (b instanceof Button) {
b.setBackgroundColor(Color.Red);
}
}

Navigating an Array (Android String Array)

I'm new to android developing but right now I'm working on an application that displays Random Facts. Since I don't want it to be in a random order, I would like to have them in a list. I would like to order through them one by one and show them using TextView.
Resources res = getResources();
myString = res.getStringArray(R.array.FactsArray);
That's what I have so far. If I'm right, that just establishes the array so I can be able to use it later. What I had before was rgenerator which chose a random string from the array and displayed it when I clicked a button.
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
fact = myString[rgenerator.nextInt(myString.length)];
TextView tv = (TextView) findViewById(R.id.text1);
tv.setText(fact);
But Like I said, I would like to just order through them one by one when a button is clicked.
Since you're displaying the strings sequentially, you'll need a counter variable to keep track of where you are in the array. It should be initialized to zero. Each time you click the button it should increment until you reach the end of the array (myString.length - 1).
As far as the actual event handling, that's not hard to do. You just need to create a setOnClickListener() for your button.
int count = 0;
Button b1 = (Button) findViewById(R.id.buttonName);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (count < myString.length) {
tv.setText(myString[count]);
count++;
}
}
});

Categories

Resources