java - 如何获得 ActionBar “customView” 宽度
问题描述
如何获得如下突出显示的工具栏/操作栏的宽度customView
?
我的想法是获得整个 screenWidth 并减去“自定义区域”的 x 坐标,但我不能/不知道如何获得它的 x 坐标。
val displayMetrics = DisplayMetrics()
activity.windowManager.defaultDisplay.getMetrics(displayMetrics)
val screenWidth = displayMetrics.widthPixels
val toolbar= mainActivity.findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbar)
val location = IntArray(2)
mainActivity.supportActionBar?.customView?.getLocationOnScreen(location)
val x = location[0]
val customViewWidth = screenWidth - x
解决方案
嗨,我有这个解决方案来获取 x 的值,它对我来说很好,这个想法是从操作栏获取工具栏,从工具栏获取 textView:
private void getX() {
// to get ViewContainer from ActionBar
int id = getWindow().getDecorView().getResources().getIdentifier("action_bar_container", "id", getPackageName());
ViewGroup v = findViewById(id);
Log.d(TAG, "onCreate() returned: " + v.getChildCount());
int childCount = v.getChildCount();
// The view tree observer can be used to get notifications when global events, like layout, happen.
v.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
for (int i = 0; i < childCount; i++) {
if (v.getChildAt(i) instanceof Toolbar) {
Toolbar toolbar = (Toolbar) v.getChildAt(i);
int toolBarChild = toolbar.getChildCount();
for (int j = 0; j < toolBarChild; j++) {
Log.e(TAG, "onCreate: " + toolbar.getChildAt(j));
if (toolbar.getChildAt(i) instanceof TextView) {
TextView tx = (TextView) toolbar.getChildAt(i);
int x = tx.getLeft();
Log.e(TAG, "onCreate: " + x); // this to get the Value of ox ( left of title )
Log.e(TAG, "onCreate: " + tx.getText()); // this return title in action bar
/*
your code
*/
}
}
}
}
}
});
}
希望对你有帮助
推荐阅读
- git - Android studio git commit 乱码
- javascript - 使用 React 的新功能:TypeError:无法读取未定义的属性“地图”
- javascript - 显示带换行符的字符串
- php - 通过自定义日期键对 PHP 多维数组进行排序
- c# - C# RegEx 匹配特定字符串
- python - 外部库导入依赖时本地文件优先
- powershell - 当帐户来自域 A 并且组来自域 B 时如何删除成员?
- python - 在 Numpy 中以编程方式沿其所有轴裁剪数组
- php - 将数量链接到 Woocommerce 中的产品变体
- python - 使用 SQLAlchemy 将用户和限制计数添加到 SQL