我有一些代码,我需要修改它以使工具栏上的文本字段居中。这是屏幕截图:Screen Shot:https://i.stack.imgur.com/MDl9c.png
以下是MainActivity.java
package life.poa.webcastman.poa1;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import java.util.ArrayList;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ListView;
import com.google.firebase.iid.FirebaseInstanceId;
import android.view.Display;
import android.graphics.Point;
import android.util.DisplayMetrics;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
public String tmpemail ;
public String tmpusername ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(life.poa.webcastman.poa1.R.layout.activity_main);
View bgimage = (View) findViewById(R.id.frame_container);
bgimage.setBackgroundResource(R.drawable.wheat);
bgimage.setAlpha(1.0f);
commonfunc.myprint("#####_____mainActivity_onCreateView ");
//if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
//{
// getWindow().setNavigationBarColor(getResources().getColor(R.color.colorPrimary));
//}
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
commonfunc.myprint("____mainactivity-onCreate 1 : " + width + " " + height);
DisplayMetrics metrics;
width = 0;
height = 0;
metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
height = metrics.heightPixels;
width = metrics.widthPixels;
commonfunc.myprint("____mainactivity-onCreate 1 : " + width + " " + height);
float density = this.getResources().getDisplayMetrics().density;
if (density >= 4.0) {
commonfunc.myprint("xxxhdpi");
}
if (density >= 3.0) {
commonfunc.myprint("xxhdpi");
}
if (density >= 2.0) {
commonfunc.myprint("xhdpi");
}
if (density >= 1.5) {
commonfunc.myprint("hdpi");
}
if (density >= 1.0) {
commonfunc.myprint("mdpi");
} else {
commonfunc.myprint("ldpi");
}
// Email
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
tmpemail = preferences.getString(commonfunc.company + "email", "");
commonfunc.myprint("mainactivity preferences email:" + commonfunc.company + "email: " + tmpemail);
// Username
tmpusername = preferences.getString(commonfunc.company + "username", "");
commonfunc.myprint("mainactivity preferences email:" + commonfunc.company + "email: " + tmpusername);
//Refresh Token
String refreshtoken = FirebaseInstanceId.getInstance().getToken();
String preftoken = preferences.getString(commonfunc.company + "token", "");
commonfunc.myprint("mainactivity preferences preftoken refreshtoken:" + preftoken + " <-> " + refreshtoken);
if (refreshtoken != preftoken) {
editor.putString(commonfunc.company + "token", refreshtoken);
editor.apply();
editor.commit();
String tmptoken = preferences.getString(commonfunc.company + "token", "");
commonfunc.myprint("mainactivity preferences token recheck:" + commonfunc.company + "token: " + tmptoken);
}
//main_started
String pref_main_started = preferences.getString(commonfunc.company + "main_started", null);
commonfunc.myprint("mainactivity_onCreateOptionsMenu_preferences main_started 1:" + commonfunc.company + "main_started " + pref_main_started);
//Gordon Turn Off main_started to null
if (pref_main_started != null) {
editor.putString(commonfunc.company + "main_started", null);
editor.apply();
editor.commit();
pref_main_started = preferences.getString(commonfunc.company + "main_started", null);
commonfunc.myprint("mainactivity_onCreateOptionsMenu_preferences pref_main_started " + commonfunc.company + "main_started " + pref_main_started);
editor.putString(commonfunc.company + "main_started", null);
}
pref_main_started = preferences.getString(commonfunc.company + "main_started", null);
commonfunc.myprint("mainactivity_onCreateOptionsMenu_preferences main_started 3:" + commonfunc.company + "main_started " + pref_main_started);
displaynav();
if (savedInstanceState == null)
{
// on first time display view for first nav item
displayView(0);
}
}
private void displaynav()
{
commonfunc.myprint("mainActivity_displaynav ");
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(life.poa.webcastman.poa1.R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources().obtainTypedArray(life.poa.webcastman.poa1.R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(life.poa.webcastman.poa1.R.id.drawer_layout);
mDrawerList = (ListView) findViewById(life.poa.webcastman.poa1.R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Login
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Create Account
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Calendar
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Live Webcast
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// Live Webcast Archive
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
// My Groups
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
// MY Group Notifications
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
if (tmpemail == null)
{
commonfunc.myprint("mainactivity_tmpemail_null:" + tmpemail);
}
if (tmpemail.isEmpty())
{
commonfunc.myprint("mainactivity_tmpemail_isempty:" + tmpemail);
}
if (tmpemail == null || tmpemail.isEmpty())
{
}
if (tmpemail.equals("webcastpoa@gmail.com"))
{
commonfunc.myprint("mainactivity_tmpemail:" + tmpemail);
// MY Play2
navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons.getResourceId(8, -1)));
// MY Table2
navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuIcons.getResourceId(8, -1)));
}
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
//getActionBar().setDisplayHomeAsUpEnabled(true);
//getActionBar().setHomeButtonEnabled(true);
//getActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.actionbar)));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
life.poa.webcastman.poa1.R.drawable.ic_drawer, //nav menu toggle icon
life.poa.webcastman.poa1.R.string.app_name, // nav drawer open - description for accessibility
life.poa.webcastman.poa1.R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
commonfunc.myprint("mainActivity_onDrawerClosed ");
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
commonfunc.myprint("mainActivity_onDrawerOpened ");
//Hide Keyboard GB
//View view = this.getCurrentFocus();
if (drawerView != null)
{
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(drawerView.getWindowToken(), 0);
getSupportActionBar().setTitle(mTitle);
}
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
//mDrawerLayout.setBackgroundResource(R.color.colorAccent);
}
/*
* Slide menu item click listener
*/
private class SlideMenuClickListener implements
ListView.OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
commonfunc.myprint("mainActivity_SlideMenuClickListener ");
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
commonfunc.myprint("mainActivity_onCreateOptionsMenu ");
getMenuInflater().inflate(life.poa.webcastman.poa1.R.menu.main, menu);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
tmpusername = preferences.getString(commonfunc.company + "username", "");
commonfunc.myprint("mainactivity preferences email:" + commonfunc.company + "email: " + tmpusername);
setTitle("Welcome " + tmpusername);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
commonfunc.myprint("mainActivity_onOptionsItemSelected ");
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case life.poa.webcastman.poa1.R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/*
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
commonfunc.myprint("mainActivity_onPrepareOptionsMenu ");
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
//Turn setting off
//menu.findItem(life.poa.webcastman.poa1.R.id.action_settings).setVisible(!drawerOpen);
menu.findItem(life.poa.webcastman.poa1.R.id.action_settings).setVisible(false);
//01-01-2017 commented
//SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
//SharedPreferences.Editor editor = preferences.edit();
//tmpusername = preferences.getString(commonfunc.company + "username", "");
//commonfunc.myprint("mainactivity preferences email:" + commonfunc.company + "email: " + tmpusername);
//setTitle("Welcome " + tmpusername);
return super.onPrepareOptionsMenu(menu);
}
/*
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
commonfunc.myprint("#####_____mainActivity_displayView ");
// update the main content by replacing fragments
Fragment fragment = null;
// We allow the Sensor to be used in all instances by default
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new login_login();
break;
case 2:
fragment = new login_create();
break;
case 3:
fragment = new calendar();
break;
case 4:
fragment = new live_webcast();
break;
case 5:
fragment = new live_webcast_archive();
break;
case 6:
/*
if (tmpemail == null || tmpemail.isEmpty())
{
commonfunc.myprint("my_group_tmpemail null or isempty:" + tmpemail);
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("You Must Create An Account To Join Groups.");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
return;
}
*/
fragment = new my_group();
break;
case 7:
fragment = new my_group_notification();
break;
case 8:
fragment = new my_play2();
break;
case 9:
fragment = new my_table2();
break;
default:
// In just this one instance, we turn the sensor off
// Until a different menu item is selected, which re-enables it
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(life.poa.webcastman.poa1.R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
//setTitle(navMenuTitles[position] + "Welcome");
//setTitle("Welcome " + tmpusername);
mDrawerLayout.closeDrawer(mDrawerList);
}
else
{
// error in creating fragment
commonfunc.myprint("MainActivity Error in creating fragment");
}
}
@Override
public void setTitle(CharSequence title) {
commonfunc.myprint("mainActivity_setTitle ");
mTitle = title;
//getActionBar().setTitle(mTitle);
getSupportActionBar().setTitle(mTitle);
}
/*
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
commonfunc.myprint("mainActivity_onPostCreate ");
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
commonfunc.myprint("mainActivity_onConfigurationChanged ");
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
activity_main.xml中
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType = "centerCrop"
/>
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"
/>
</android.support.v4.widget.DrawerLayout>
drawer_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="@drawable/list_selector">
<ImageView
android:id="@+id/icon"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:contentDescription="@string/desc_list_item_icon"
android:src="@drawable/ic_home"
android:layout_centerVertical="true" />
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="@id/icon"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="@color/list_item_title"
android:gravity="center_vertical"
android:paddingRight="40dp"/>
<TextView android:id="@+id/counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/counter_bg"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="8dp"
android:textColor="@color/counter_text_color"/>
</RelativeLayout>
答案 0 :(得分:0)
不要做太多事情,你可以通过导航设置你的空间..
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setContentInsetStartWithNavigation(50);
setSupportActionBar(toolbar);
toolbar.setTitle(title);
答案 1 :(得分:0)
必须在标题上添加一个边距才能让它居中,谢谢