【问题标题】:How to align title of Activity on center or anywhere in android?如何在中心或android中的任何位置对齐Activity的标题?
【发布时间】:2011-09-28 00:09:07
【问题描述】:
((TextView)((FrameLayout)((LinearLayout)((ViewGroup)getWindow().getDecorView()).getChildAt(0)).getChildAt(0)).getChildAt(0)).setGravity(Gravity.CENTER);

我已经使用上面的代码来对齐我在center 中的活动标题,但它会给我一个错误,即“FrameLayout 无法解析为一个类型”,如果删除FrameLayout 那么它会给我LinearLayout 中的相同错误。我还通过添加以下行通过android.xml 文件更改标题栏:

          <application  android:label="@string/app_name">
          <activity android:name=".OptionsmenuAct"
              android:label="@string/app_name"

              android:theme="@android:style/Theme.Translucent">

         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        </activity>

现在我正在尝试根据我的需要align,并且还想增加title text 的大小。

我该怎么做,请帮助我............

【问题讨论】:

    标签: android layout alignment


    【解决方案1】:

    您实际上需要为此使用自定义标题视图。看看这个问题:how to set custom title bar TextView Value dynamically in android?

    【讨论】:

      【解决方案2】:
      ((TextView)((LinearLayout)((ViewGroup) getWindow()
         .getDecorView()).getChildAt(0)).getChildAt(0)).setGravity(Gravity.CEN‌​TER); 
      

      这对我有用。 但这是一种无证的做法。众所周知,谷歌会从根本上改变未记录的数据结构,并且不能保证这种特殊技术在未来会奏效。所以我会推荐你​​在 try/catch 块中使用它,比如:

      try {   
      ((TextView)((LinearLayout)((ViewGroup) getWindow()
         .getDecorView()).getChildAt(0)).getChildAt(0)).setGravity(Gravity.CENTER);
              } catch (Exception e1) {
                  e1.printStackTrace();
              }
      

      【讨论】:

        【解决方案3】:

        我做了一点 usman 方法的变体:

        ((TextView)getWindow().getDecorView().findViewById(android.R.id.title)).setGravity(Gravity.CENTER);
        

        【讨论】:

        • getChildAt(0)).getChildAt(0) 在 Android 5.1 上不起作用,findViewById(android.R.id.title) 起作用。另外,为了安全起见,我建议在 try {} catch 中检查 findViewById 的结果是否为 null 和 wrap (TextView) 类型转换
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-29
        • 1970-01-01
        • 2020-10-10
        • 2020-03-09
        • 2013-08-27
        • 2022-12-06
        • 1970-01-01
        相关资源
        最近更新 更多