这里有一个建议: 你可以得到 ID(例如由 android:id="@+id/..My Str..指定) ,它是由 R通过使用它的给定名称(例如 My Str)生成的。使用 getIdentifier()方法的代码片段将是:
public int getIdAssignedByR(Context pContext, String pIdString)
{
// Get the Context's Resources and Package Name
Resources resources = pContext.getResources();
String packageName = pContext.getPackageName();
// Determine the result and return it
int result = resources.getIdentifier(pIdString, "id", packageName);
return result;
}
在 Activity中,与 findViewById结合使用的例子是:
// Get the View (e.g. a TextView) which has the Layout ID of "UserInput"
int rID = getIdAssignedByR(this, "UserInput")
TextView userTextView = (TextView) findViewById(rID);
private ArrayList<View> getAllChildren(View v) {
if (!(v instanceof ViewGroup)) {
ArrayList<View> viewArrayList = new ArrayList<View>();
viewArrayList.add(v);
return viewArrayList;
}
ArrayList<View> result = new ArrayList<View>();
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
ArrayList<View> viewArrayList = new ArrayList<View>();
viewArrayList.add(v);
viewArrayList.addAll(getAllChildren(child));
result.addAll(viewArrayList);
}
return result;
}
要使用这个结果,你可以这样做:
// check if a child is set to a specific String
View myTopView;
String toSearchFor = "Search me";
boolean found = false;
ArrayList<View> allViewsWithinMyTopView = getAllChildren(myTopView);
for (View child : allViewsWithinMyTopView) {
if (child instanceof TextView) {
TextView childTextView = (TextView) child;
if (TextUtils.equals(childTextView.getText().toString(), toSearchFor)) {
found = true;
}
}
}
if (!found) {
fail("Text '" + toSearchFor + "' not found within TopView");
}