簡體   English   中英

Android-如何向工具欄后退按鈕添加ID?

[英]Android - How to add id to Toolbar back button?

為了進行自動化測試,我需要在工具欄的“ 后退/菜單”按鈕視圖中添加ID

我嘗試使用getChildAtsetId添加ID,但是在檢查視圖層次結構時仍未設置ID。 在我的情況下, android.R.id.home菜單ID無效。 當我使用Layout inspector檢查視圖層次時,需要為視圖設置的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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM