如何在活动中对齐标题或标签的中心?

exc*_*n01 6 android label title android-activity

我知道有两种设置活动标题的方法.一种方法是在android清单中设置它,如android:label ="@ string/app_name".第二个是在活动类中以编程方式设置,如setTitle("Hello World!").两种方式都位于左侧,但我如何将其放在中心?

Cha*_*itu 21

它会工作正常..

TextView customView = (TextView) 
LayoutInflater.from(this).inflate(R.layout.actionbar_custom_title_view_centered, 
     null); 

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

customView.setText("Some centered text"); 
getSupportActionBar().setCustomView(customView, params); 
Run Code Online (Sandbox Code Playgroud)


Ted*_*opp 5

您需要定义自定义标题样式/主题.查看com.example.android.apis.app.CustomTitle的示例.


exc*_*n01 5

我找到了另一种设置标题中心的方法,只需将代码放在setContentView(R.layout.new)下面......

((TextView)((FrameLayout)((LinearLayout)((ViewGroup) getWindow().getDecorView()).getChildAt(0)).getChildAt(0)).getChildAt(0)).setGravity(Gravity.CENTER);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.谢谢!

  • 唯一的问题是它依赖于窗口内容结构的无证方面.众所周知,谷歌彻底改变了未记录的数据结构,并且无法保证这种特殊技术将来能够发挥作用. (14认同)
  • 好吧,谷歌糟透了(在os设计)它并不适合我.但这样做:((TextView)((LinearLayout)((ViewGroup)getWindow().getDecorView()).getChildAt(0)).getChildAt(0)).setGravity(Gravity.CENTER); (3认同)
  • @TedHopp谷歌众所周知,从根本上改变*记录的*数据结构......忽略了向后兼容性,每次我决定升级任何Android SDK或开发工具时都会让我的生活变得悲惨.我会说:做什么有效*现在*.无论如何它都会破裂,无论如何你都需要修理它.无论是否记录在案. (2认同)

Chl*_*loe 5

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // must come before setContentView
   setContentView(R.layout.activity_calculator); 
   getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
Run Code Online (Sandbox Code Playgroud)

将您的布​​局放在 layout/title_bar.xml 中

<?xml version="1.0" encoding="utf-8"?>
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/myTitle"
  android:text="Custom Centered Title"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:textColor="@android:color/black"
  android:gravity="center"
   />
Run Code Online (Sandbox Code Playgroud)

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/2.2_r1.1/com/example/android/apis/app/CustomTitle.java