[英]How to align center item in an Action bar on Android
我有一個帶有3個菜單項的操作欄,可悲的是,這些菜單項在左側對齊,我將在中央對齊。 我一直在環顧四周,嘗試了一些東西,但沒有任何效果。
到目前為止,這是我的代碼:
public class Layout extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actionbar);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.actionbar);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.action_refresh:
Toast.makeText(this, "Refresh selected", Toast.LENGTH_SHORT)
.show();
break;
// action with ID action_settings was selected
case R.id.action_settings:
Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT)
.show();
break;
default:
break;
}
return true;
}
}
這是我的R.layout.action:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="my Title"
android:textColor="#ffffff"
android:id="@+id/mytext"
android:textSize="18sp"
android:gravity="center"
/>
事實是,您實際上不應該將ActionBar(或Toolbar,取決於您使用的工具)中的Text居中對齊-這就是為什么這樣做不那么簡單。
如果您將其對齊,保持當前狀態,則應與72dp關鍵線對齊(這將與常規“材料指南”相匹配)。
您可以在以下位置找到這些規范: https : //www.google.com/design/spec/layout/structure.html#structure-app-bar (但同樣,如果您什么也不做,一切都應該可以正常工作)
看到了,您可能已經看到某些應用程序在操作欄(工具欄)上具有居中文本,但是必須自定義布局或使用基本編碼,API應當大於5.0才能實現這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.