I'm having trouble implementing a Toolbar in my Android application. I have several problems, really.
First off, here's my MainActivity.java :
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar_Main);
toolbar.setLogo(R.drawable.logo);
toolbar.setTitle(R.string.app_name);
toolbar.inflateMenu(R.menu.main_actions);
setActionBar(toolbar);
}
}
activity_main.xml :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:nestedScrollingEnabled="false">
<Toolbar
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:id="@+id/toolbar_Main"
android:background="?android:attr/colorPrimary" />
<!-- There's an EditText here, but I think that's not the problem -->
</LinearLayout>
styles.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="android:Theme.Material.Light">
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:colorPrimary">@color/primaryColor</item>
<item name="android:colorPrimaryDark">@color/primaryColorDark</item>
</style>
</resources>
The problems I'm having are:
Now the first problem I can fix by removing the setActionBar
part (not sure if that's good practice though), but second one, not so much. The logo and text remain centered no matter what I try. I've tried setting the Toolbar's gravity to top|left
, as well as some other things, all to no avail.
When searching on Google (or StackOverflow), all I get are results asking to center the text, which is what I don't want.
I should also mention that I'm developing the app only for API level 21, so no AppCompat and all that fancy stuff, just a Toolbar that I wish to use as the app's main ActionBar.
I'm probably just missing some tiny thing, so thanks in advance.
To me:
setActionBar()
call; inflateMenu()
line and inflate the menu during onCreateOptionsMenu()
, as usual; Title and logo issues, as well as menu disappearing, might be due to:
<item name="android:windowNoTitle">true</item> <item name="android:windowActionBar">false</item>
Why these lines? Just remove them if you don't need.
If this doesn't fix, try calling setActionBar(toolbar)
first, and then set title using getActionBar().setTitle()
. However I'm pretty sure that removing the two window lines from your style will be enough, so do that first.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.