Android-如何将id添加到工具栏后退按钮?

Android-如何将id添加到工具栏后退按钮?,android,android-toolbar,Android,Android Toolbar,出于自动测试的目的,我需要将ID添加到工具栏的后退/菜单按钮视图中 我尝试使用getChildAt和setId添加id,但在检查视图层次结构时,id仍然没有设置android.R.id.home菜单id在我的情况下不起作用。我需要在使用布局检查器检查视图层次结构时为视图设置的id。只有这样,id才能用于自动UI测试 你能建议一种方法吗?工具栏的后退/菜单按钮已经idandroid.R.id.home 你可以使用这个id 要对该文件执行操作,请使用下面的代码 @Override public b

出于自动测试的目的,我需要将ID添加到工具栏的后退/菜单按钮视图中

我尝试使用
getChildAt
setId
添加id,但在检查视图层次结构时,id仍然没有设置
android.R.id.home
菜单id在我的情况下不起作用。我需要在使用布局检查器检查视图层次结构时为视图设置的id。只有这样,id才能用于自动UI测试


你能建议一种方法吗?

工具栏的后退/菜单按钮已经id
android.R.id.home
你可以使用这个id

要对该文件执行操作,请使用下面的代码

 @Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == android.R.id.home) {
        Toast.makeText(context, "Backarrow pressed", Toast.LENGTH_SHORT).show();
        return true;
    }

    return false;
}

在活动的底部添加此代码

@Override
    public void onBackPressed() {
        super.onBackPressed();
    }

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_menuname, menu);
        return true;
    }
@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Ward/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
            switch (item.getItemId()) {
           case android.R.id.home:
                    finish();
                    return true;
            }
       }

我可以通过搜索
AppCompatImageButton
并设置第一个找到的视图的id,将id添加到工具栏后退按钮。在设置actionBar之后执行此操作非常重要

private void addIdToBackButton() {
     for (int i = 0; i < toolbar.getChildCount(); i++) {
        View child = toolbar.getChildAt(i);
        if (child instanceof AppCompatImageButton) {
            child.setId(R.id.toolbar_back_button);
            return;
        }
     }
 }

private void setUpActionBar() {
    setSupportActionBar(toolbar);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle("Title");
    actionBar.setDisplayHomeAsUpEnabled(true);
    toolbar.setNavigationOnClickListener(__ -> onBackPressed());

    addIdToBackButton();
}
private void addedtobackbutton(){
对于(int i=0;ionBackPressed());
AddedToBackButton();
}

我只是建议将有助于在xml文件中的drawable文件夹中创建xml文件put
android:drawable=“@drawable/your_icon”
android:id=“@+id/your_id”
然后使用
getSupportActionBar().setHomeAsUpIndicator(R.drawable.your_xml_文件)这样行吗?你能告诉我们你是如何设置ID的吗?这对我来说是正常的。@MarioKutlev创建一个自定义工具栏并将自定义图像设置为BACK/MENU,这样您就可以为该图像分配一个新的id了