我正在使用ActionBarActivity并尝试使用以下命令获取主页按钮(汉堡)的位置:
View home = findViewById(android.support.v7.appcompat.R.id.home);
和/或
View home = findViewById(android.R.id.home);
问题是我总是得到null。 有谁知道如何获得视图?也许我想从错误的地方拿到它
我试图从OnCreateOptionsMenu(菜单菜单)
获取它答案 0 :(得分:2)
这样做:
getActionBar().setHomeButtonEnabled(true);
View home = findViewById(android.R.id.home);
答案 1 :(得分:1)
答案 2 :(得分:1)
为避免代码在将来消失,我只是复制了@rendellhb提供的Gist
public class ToolbarNavigationUtil {
public static View getToolbarNavigationIcon ( Toolbar toolbar ){
//check if contentDescription previously was set
boolean hadContentDescription = TextUtils. isEmpty(toolbar.getNavigationContentDescription());
String contentDescription = !hadContentDescription ? toolbar.getNavigationContentDescription().toString() : "navigationIcon" ;
toolbar . setNavigationContentDescription(contentDescription);
ArrayList< View > potentialViews = new ArrayList< View >();
//find the view based on it's content description, set programatically or with android:contentDescription
toolbar . findViewsWithText(potentialViews,contentDescription, View . FIND_VIEWS_WITH_CONTENT_DESCRIPTION );
//Nav icon is always instantiated at this point because calling setNavigationContentDescription ensures its existence
View navIcon = null ;
if (potentialViews . size() > 0 ){
navIcon = potentialViews . get( 0 ); //navigation icon is ImageButton
}
//Clear content description if not previously present
if (hadContentDescription)
toolbar . setNavigationContentDescription( null );
return navIcon;
}
public static TextView getToolbarTitleView ( ActionBarActivity activity , Toolbar toolbar ){
ActionBar actionBar = activity . getSupportActionBar();
CharSequence actionbarTitle = null ;
if (actionBar != null )
actionbarTitle = actionBar . getTitle();
actionbarTitle = TextUtils . isEmpty(actionbarTitle) ? toolbar . getTitle() : actionbarTitle;
if ( TextUtils . isEmpty(actionbarTitle)) return null ;
// can't find if title not set
for ( int i = 0 ; i < toolbar . getChildCount(); i ++ ){
View v = toolbar . getChildAt(i);
if (v != null && v instanceof TextView ){
TextView t = (TextView) v;
CharSequence title = t . getText();
if ( ! TextUtils . isEmpty(title) && actionbarTitle . equals(title) && t . getId() == View . NO_ID ){
//Toolbar does not assign id to views with layout params SYSTEM, hence getId() == View.NO_ID
//in same manner subtitle TextView can be obtained.
return t;
}
}
}
return null ;
}
}
答案 3 :(得分:0)
这是我的解决方案,对我有用。
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
Log.d("checksize",toolbar.getChildCount()); \\print 1, this child is title
setSupportActionBar(toolbar);
Log.d("checksize",toolbar.getChildCount()); \\print 2
View navIcon = toolbar.toolbar.getChildAt(1);
答案 4 :(得分:0)
这对我有用:
然后这样查询home键
使用 Kotlin: val image = toolbar.getChildAt(1) as AppCompatImageButton
使用 Java: AppCompatImageButton imageButton = (AppCompatImageButton)toolbar.getChildAt(1)