Custom theme in Android / Xamarin project - center Title text of Action Bar

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

I have custom theme in Android / Xamarin project. What I can't do is to:

  • set header to the middle (and remove icon)
  • add menu button with menu option (for example button settings)

I've tried with settings property -> gravity to center but it didn't work.

    

回答1:

You will have to do it programmatically via a static method inside a static class

public static void SetActionbarText(Activity activity, string text)         {             // Setting custom view enable             activity.ActionBar.SetHomeButtonEnabled(false);             activity.ActionBar.SetIcon(Android.Resource.Color.Transparent);             activity.ActionBar.SetDisplayShowCustomEnabled(true);             activity.ActionBar.Title = "";              LinearLayout linearLayout = new LinearLayout(activity);             linearLayout.SetGravity(GravityFlags.CenterVertical);             LinearLayout.LayoutParams textViewParameters =                  new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent);             textViewParameters.RightMargin = (int)(40 * activity.Resources.DisplayMetrics.Density);             TextView modelTitle = new TextView(activity);                     modelTitle.Text = text;             modelTitle.Gravity = GravityFlags.Center;             linearLayout.AddView(modelTitle,textViewParameters);             ActionBar.LayoutParams actionbarParams =                  new ActionBar.LayoutParams(ActionBar.LayoutParams.MatchParent,ActionBar.LayoutParams.MatchParent);             activity.ActionBar.SetCustomView(linearLayout, actionbarParams);         }

Notice that you have to play with right margin dimension of the text. This margin should be equal as width of the home icon(it is there but it is invisible).

You can add the right icon adding it on a Menu.xml and inflating this xml file in the OnCreateOptionsMenu method of your activity.



回答2:

You can also do it by using menu and styles xml files. To add the settings button, for example, you can just add an item in the menu file that defines the menu of the UI shown in the picture. There are a few predefined icons, like the one that i have used (ic_menu_preferences), but you can use another one or use a image instead. So, in, let`s say agrippa_menu.xml:

 

[...]

[...]

Center Align title in action bar using styles in android. : . If someone knows how to do it using just styles will be welcomed.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!