我想使用java代码在动作栏中居中对齐动态标题。根据String变量CoName,我的标题每次都会改变。请帮我把ActionBar的标题放在中心位置。提前致谢!
我的android活动java代码是:
public class BaseActivity extends ActionBarActivity
{
private static final int MENU_ITEM1 = 0;
private static final int MENU_ITEM2 = 1;
private static final int MENU_ITEM3 = 2;
private static final int Menu_ITEM4 = 3;
private ImageButton SalesButton;
private SharedPreferences SharedPreferences;
//private String UserName;
private TextView tv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.baseactivity);
SharedPreferences =getSharedPreferences(PREF_NAME, LoginActivity.MODE_PRIVATE);
CoName = SharedPreferences.getString("CONAME", null);
Username = SharedPreferences.getString("USERNAME", null);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
getSupportActionBar().setCustomView(R.layout.baseactivity);
actionBar.setTitle(CoName);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, MENU_ITEM1, Menu.NONE, Username);
getMenuInflater().inflate(R.menu.commonmenu, menu);
//menu.add(Menu.NONE, MENU_ITEM2, Menu.NONE, "Setting");
//menu.add(Menu.NONE, MENU_ITEM3, Menu.NONE, "Refresh");
//menu.add(Menu.NONE, Menu_ITEM4, Menu.NONE,"Log Out");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case MENU_ITEM1 :
Toast.makeText(this, "Clicked: Menu No. 1", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu2:
Toast.makeText(this, "Clicked: Menu No. 2 ", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu3 :
Toast.makeText(this, "Clicked: Menu No. 3 ", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu4:
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
default:
return super.onOptionsItemSelected(item);
}
}
}
答案 0 :(得分:0)
使用
try getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
而不是使用
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);