For loop with object names - android

If I have an array of buttons in android and want to get these buttons (findviewbyid) through a for loop how do i do this? Lets say I have in my xml defined button1, button2 and button3. How do I assign arr[0],arr[1] and arr[2] to these?
for(int a = 0; a < arr.length; a++){
arr[a] = (Button) findViewById(R.id.button[a + 1]); //Doesn't work
}
Thanks in advance!

Try to implement this:
for(int a=0; a<arr.length; a++) {
String buttonID = "btn" + a;
int resID = getResources().getIdentifier(buttonID, "id", "com.package.your_app");
// To fetch Package name, you can directly call getPackageName() instead of static string "com.package.your_app
buttons[a] = ((Button) findViewById(resID));
buttons[a].setOnClickListener(this);
}

Then this work:
for(int a = 0; a < arr.length; a++) {
String buttonId = "btn" + String.valueOf(a);
int resButton = getResources().getIdentifier(buttonId, "id", "com.package.your_app");
arr[a] = (Button) findViewById(resButton);
}

Related

How can i add as well as remove layout pragmatically in android?

I want to work as AutoCompleteTextview. But I am not using auto complete text view in my project. I have used edit text and taking it the value for sorting the value of adapter using those values of adapter I am creating a dynamic button. But actually, I want to delete dynamically created button. When a user enters new value in edit text at that case it sorts new value in adapter according to the button has to created. But, my problem is that dynamically created button does not get deleted when a user enters new text on edit text view. It has to looking like this:
if (!s.equals("")) {
final String query = s.toString().trim();
filteredTags.clear();
((ViewManager) btnTag.getParent()).removeView(btnTag);
for (int i = 0; i < TagArray.size(); i++) {
final String tagName = TagArray.get(i).gettagName();
if (tagName.contains(query)) {
filteredTags.add(TagArray.get(i));
}
}
count1 = filteredTags.size();
layout = (LinearLayout) dialog.getCustomView().findViewById(R.id.layoutTags);
layout.setOrientation(LinearLayout.VERTICAL); //Can also be done in xml by android:orientation="vertical"
layout.setWeightSum(1);
float rowneed = ((float) count1 / 5);
k = 0;
for (int i = 0; i < ceil(rowneed); i++) {
row1 = new LinearLayout(getContext());
row1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
/* layout.setVisibility(View.VISIBLE);
row.setVisibility(View.VISIBLE);*/
for (int j = 0; j < 5; j++) {
btnTag = new Button(getContext());
btnTag.setHeight(15);
btnTag.setWidth(0);
btnTag.setMinimumWidth(155);
btnTag.setMinimumHeight(135);
mTagList1 = new ArrayList<>();
if (k < count1) {
btnTag.setText(filteredTags.get(k).gettagName());
btnTag.setId(k);
k++;
btnTag.setVisibility(View.VISIBLE);
} else {
btnTag.setVisibility(View.INVISIBLE);
}
Log.e("count", " " + k + " " + count1 + " " + ceil(rowneed) + " " + edtTag.getText().toString());
btnTag.setTextSize(7);
btnTag.setGravity(0);
row1.addView(btnTag);
}
layout.addView(row1);
}
for (int btnId = 0; btnId < filteredTags.size(); btnId++) {
btnTag = (Button) dialog.getCustomView().findViewById(btnId);
final int finalId1 = btnId;
btnTag.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
TagNameArray.add(new Tags(filteredTags.get(finalId1).gettagId(), filteredTags.get(finalId1).gettagName()));
// Log.e("button","Button clicked index = " + finalId +" "+ TagArray.get(finalId1).gettagName()+" "+TagNameArray.size());
}
});
}
}
Add this line of code :
layout.removeAllViews();
layout.invalidate();
row.removeAllViews();
row.invalidate();
This might help you, give me a feedback for what you got, wish I help you
set a dynamic tag for btnTag for example
btnTag.setTag(DynamicTagInt++);
and then
row1.removeView(btnTag.findViewById(DynamicTagInt));
//DynamicTagInt= the desired button that you want to delete
or by the ID of the button for example
row1.removeView(btnTag.findViewWithTag(k));

Android : How to add IDs Views to R.java dynamically with String resources?

I've created some buttons dynamically, when i start activity all is well, but when i rotate a screen or press back Button, i lose all buttons, i've googled then i've found that the views without IDs can't be saved, so i want to set IDs for them dynamically and i want to find them inside R.java file with there name like this :
public static final class id {
public static final int Button1=0x7f070027;
public static final int Button2=0x7f070024;
}
I've tried setId() but the problem is not solved, and i think it's not the same thing when use setID(); and set id manually inside String file, so i need your help thanks in advance(^_^).
here's my source code :
TableLayout TL = (TableLayout) findViewById(R.id.tlRDV);
TL.removeAllViews();
j = 0;
for (int i = 0; i < nbH; i++) {
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
tr.setId(View.generateViewId());
TextView text_view = new TextView(this);
Button b = new Button(this);
text_view.setWidth(1000);
j = j + averageConsultationTime;
HMA = ((BeganConsultationH * 60) + (BeganConsultationM))
+ j - averageConsultationTime;
int h = HMA / 60;
int m = HMA % 60;
b.setBackgroundColor(0xff99cc00);
b.setText(h + "H" + m);
tr.addView(b);
for (int k = 0; k < 7; k++) {
Button but = new Button(this);
but.getId(View.generateViewId());
but.setText("" + but.getId());
but.setOnClickListener(getOnClickDoSomething(but,
jours[k] + "_" + h + "H" + m));
tr.addView(but);
}
TL.addView(tr);
}
}
}
}

400 ImageViews and a For, in Android

I'm making an layout with 400 imageView. The question is how I can set R.id.imageView>>i<<
for(int i = 1; i < 401; i++){
ImageView imageView = (ImageView)findViewById(R.id.imageView-i-);
}
for (int i = 1; i <= 400; i++) {
String s = "imageview" + i;
int id = getResources.getIdentifier(s, "id", getPackageName ());
ImageView imageview = (ImageView)findViewById (id);
}
This should work

how to convert int into string in forloop

I want to print json array utrition arrray in textview dynamically problem is that if I write"1" in this line (school3.getJSONObject("1"));
then its print only first "name" and "Qty" from json. I want to write j at this line but problem is it shows error The method getJSONObject(String) in the type JSONObject is not applicable for the arguments (int)
for (int j = 1
school3.getJSONObject(j)
is there any method convert int j= string then add in
school3.getJSONObject(j) like this way
//for example
string z;
z=j.tostring();
school3.getJSONObject(z);
{
"status":1,
"data"
,
"dish_nutrition":
{
"1":
{
"name":"Cholesterol and Diet",
"qty":"2"
},
"2":
{
"name":"Cholesterol and Diet",
"qty":"1"
}
}
}
JSONObject school3 = json2.getJSONObject("dish_nutrition");
final TableLayout table = (TableLayout) findViewById(R.id.table2);
for (int j = 1; j < school3.length(); j++) {
final View row = createRow (school3.getJSONObject("1"));
table.addView(row);
num=num+1;
}
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView)
row.findViewById(R.id.localTime)).setText(item.getString("name"));
((TextView)
row.findViewById(R.id.apprentTemp)).setText(item.getString("qty"));
return row;
}
Use Integer.toString(int) or use int+"" in converts the integer to string like j+""
for (int j = 1; j < school3.length(); j++) {
final View row = createRow (school3.getJSONObject(j+""));
table.addView(row);
num=num+1;
}
OR
for (int j = 1; j < school3.length(); j++) {
final View row = createRow (school3.getJSONObject(Integer.toString(j)));
table.addView(row);
num=num+1;
}
String z = String.valueOf(j);
school3.getJSONObject('\"' + z + '\"');
Integer to string?
Integer.toString(i)
You can do something like this :
school3.getJSONObject('\"' + j + '\"');
If you need to convert int into string just use String.valueof(int values);
and if u need to convert string to int use
Integer.parseInt(string values);
Through it is basic java. you should know that.
String.valueof(int values) to convert Int to String
Integer.parseInt(string values) to convert String to Int

How do you loop through view id's?

For my android app I need to make an array of View ID's.
The array will hold 81 values so it's quite lengthy to add them one by one.
This is how it looks now:
cells[0] = R.id.Square00;
cells[1] = R.id.Square01;
cells[2] = R.id.Square02;
cells[3] = R.id.Square03;
cells[4] = R.id.Square04;
cells[5] = R.id.Square05;
//All the way to 80.
Is there a shorter/more efficient way of doing this?
Thankfully, there is. Use getIdentifier():
Resources r = getResources();
String name = getPackageName();
int[] cells = new int[81];
for(int i = 0; i < 81; i++) {
if(i < 10)
cells[i] = r.getIdentifier("Squares0" + i, "id", name);
else
cells[i] = r.getIdentifier("Squares" + i, "id", name);
}
Sam's answer is better but i think i should share an alternative
int [] ids = new int [] {R.id.btn1, R.id.btn2, ...};
Button [] arrayButton = new Button[ids.length];
for(int i=0 ; i < arrayButton.length ; i++)
{
arrayButton[i] = (Button) findViewById(ids[i]);
}
Modified form of Sam Answer
No need of if else use Integer String Formating
Resources r = getResources();
String name = getPackageName();
int[] resIDs = new int[81];
for(int i = 0; i < 81; i++)
{
resIDs[i] = r.getIdentifier("Squares0" + String.format("%03d", i), "id", name);
}

Categories

Resources