How to align center the title or label in activity?

后端 未结 4 2045
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 13:15

I know there are two ways of setting the title of activity. One way is the setting it in the android manifest like this android:label=\"@string/app_name\".

相关标签:
4条回答
  • 2020-12-01 13:52
    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);
    

    Put your layout in 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"
       />
    

    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

    0 讨论(0)
  • 2020-12-01 13:54

    It will work fine..

    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); 
    
    0 讨论(0)
  • 2020-12-01 14:01

    You will need to define a custom title style/theme. Look in the samples for com.example.android.apis.app.CustomTitle.

    0 讨论(0)
  • 2020-12-01 14:04

    I found another way of setting the title center, just put the code under the setContentView(R.layout.new)...

    ((TextView)((FrameLayout)((LinearLayout)((ViewGroup) getWindow().getDecorView()).getChildAt(0)).getChildAt(0)).getChildAt(0)).setGravity(Gravity.CENTER);
    

    Hope this helps. Thanks!

    0 讨论(0)
提交回复
热议问题