Accessing Resources Through Ids In A Loop
I have long list of EditText elements in a layout actually these are for taking matrix inputs and matrix size can vary 3x3 5x5 ... The ids of the elements are in a series pattern l
Solution 1:
I do something like that. I have 6 variations of resources in one place I need to read.
for (int i = 0; i < 6; i++ ){
String fname = "p" + i;
intid = context.getResources().getIdentifier(fname, "drawable", "com.example.yourproject");
if (id == 0) {
Log.e(TAG, "Lookup id for resource '"+fname+"' failed");
// graceful error handling code here
}
scoresBm[i] = (Bitmap) BitmapFactory.decodeResource(context.getResources(), id);
}
Solution 2:
Better Approach
Example for accessing raw resources.
ArrayList<Integer> id = new ArrayList<Integer>();
for (int i = 0; i <= 10; i++) {
id.add(getResources().getIdentifier("d"+i, "raw", getPackageName()));
}
Solution 3:
its better to do it pragmatically for example create new xml Layout
layout.xml
content only
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/parent"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ></LinearLayout>
now in your activity add views to the layout for loop example
LinearLayoutparent= (LinearLayout) findViewById(R.id.parent);
for(int i=0;i<10;i++)
{
EditTextetext=newEditText(this);
//the Id and Tag must be set to call it back if we need info from this field
etext.setId(i);
etext.setTag("kernel"+i);
//add edit text info here such as values and h/w etc
etext.setText("my id : "+i+" , My Tags is : t"+i);
//now add EditText field to parent
parent.addView(etext);
}
and to call any EditText or any other view was added pragmatically , you can call it from tag or id for example
//getlast element added from loop by id
EditText last= (EditText) parent.findViewById(10);
//orgetby tag
EditText last= (EditText) parent.findViewWithTag("kernel10");
hope this help
Post a Comment for "Accessing Resources Through Ids In A Loop"