gpt4 book ai didi

android - 如何在Android中将操作栏的标题设置在中心

转载 作者:行者123 更新时间:2023-12-05 00:10:03 26 4
gpt4 key购买 nike

您好,我正在开发演示应用程序,我需要在其中心的 ActionBar 中设置标题。我尝试了一些对我不起作用的 SO 帖子。我在 Android 4.3 手机上试用。

https://stackoverflow.com/a/21770534/2455259 , https://stackoverflow.com/a/19244633/2455259

但对我没有任何作用。有什么方法可以使用 appcompat 将 ActionBar 的标题设置为在 Android 中居中?

我正在这样做,但标题仍然在左侧。

center_action_bar_title.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp" />

Activity 中

TextView customView = (TextView)
LayoutInflater.from(getActivity()).inflate(R.layout.center_action_bar_title,
null);

ActionBar.LayoutParams params = new
ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);

customView.setText(text);
((ActionBarActivity)getActivity()).getSupportActionBar().setCustomView(customView, params);

最佳答案

我知道这个问题很老,但我能够找到解决方案。

不需要您创建自定义操作栏的解决方案。

private void centerTitle() {
ArrayList<View> textViews = new ArrayList<>();

getWindow().getDecorView().findViewsWithText(textViews, getTitle(), View.FIND_VIEWS_WITH_TEXT);

if(textViews.size() > 0) {
AppCompatTextView appCompatTextView = null;
if(textViews.size() == 1) {
appCompatTextView = (AppCompatTextView) textViews.get(0);
} else {
for(View v : textViews) {
if(v.getParent() instanceof Toolbar) {
appCompatTextView = (AppCompatTextView) v;
break;
}
}
}

if(appCompatTextView != null) {
ViewGroup.LayoutParams params = appCompatTextView.getLayoutParams();
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
appCompatTextView.setLayoutParams(params);
appCompatTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
}
}
}

然后,只需在您的 onCreate() 上调用它:

centerTitle();

就是这样。就这么简单。
希望对某人有所帮助。

关于android - 如何在Android中将操作栏的标题设置在中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25065287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com