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". Second is programmatically setting in activity class like setTitle("Hello World!"). Both ways are positioned in the left side but how can I put it in the center?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You will need to define a custom title style/theme. Look in the samples for com.example.android.apis.app.CustomTitle.
回答2:
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);
回答3:
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!
回答4:
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