[英]Android - How to add id to Toolbar back button?
為了進行自動化測試,我需要在工具欄的“ 后退/菜單”按鈕視圖中添加ID 。
我嘗試使用getChildAt
和setId
添加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.