为什么firstId
不等于secondId
? firstId
是错误的,secondId
是正确的。
如何“强制”getIdentifier
搜索正确的search_button
?
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
int firstId = getResources().getIdentifier("android:id/search_button", null, null);
int secondId = recursiveLoopChildren(searchView, "search_button").getId();
return true;
}
public View recursiveLoopChildren(ViewGroup p_parent, String p_resourceName) {
View view = null;
for (int i = p_parent.getChildCount() - 1; i >= 0; i--) {
final View child = p_parent.getChildAt(i);
if (child instanceof ViewGroup) {
View returnedChild = recursiveLoopChildren((ViewGroup) child, p_resourceName);
if(returnedChild != null) {
view = returnedChild;
break;
}
} else {
String entryName = getResources().getResourceEntryName(child.getId());
if (child != null && entryName.equals(p_resourceName)) {
view = child;
break;
}
}
}
return view;
}
答案 0 :(得分:1)
像这样调用getIdentifier():
int firstId = getResources().getIdentifier("search_button", "id", getPackageName());
然后它应该返回正确的id。
答案 1 :(得分:0)
试试这个
final View child = p_parent.getChildAt(i - 1);
如果不起作用..试试这个条件..
for (int i = p_parent.getChildCount(); i > 0; i--)