First, I know there are a lot of SO that address similar issues. I've scoured them all, and none of the provided answers are helping to solve my issue.
I cannot get the title (or back button) to appear on my android.support.v7.widget.Toolbar component. No matter what I've tried.
I have an Android activity that that looks like (my_activity.xml):
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable name="infos" type="com.mycompany.orm.adapters.ListViewAdapter"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/buttonBackground"
android:elevation="4dp"
android:logo="#drawable/ic_close_white_24dp" />
<ListView
android:id="#+id/my_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/windowBackground"
bind:items="#{infos.list}"/>
</RelativeLayout>
</layout>
And the activity onCreate as (MyActivity.java):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
if (toolbar != null) {
toolbar.setTitle("My Name Here"); // Never shows up
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setTitle("Hello World!"); // Never shows up
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_close_white_24dp);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.show();
}
}
}
But using this code, I only see a blank toolbar. I never see the text (either My Name Here or Hello World!. However, if I add the line bind:title="Testing" to the Toolbar element of the XML, I see the title appearing as Testing. However, I want to be able to manipulate the look of the toolbar/actionbar, so I would like to be able to do it in code.
Does anyone see where this might be going wrong?
Try to set label in your AndroidManifest.xml like that
<activity
android:name="yourpackagename.Activity"
android:label="My Name Here"/>
Otherwise if you want to set as programmatically
If You using extends AppCompatActivity class use
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("My Name Here");
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
If You using extends Activity class use
ActionBar ab = getActionBar();
ab.setTitle("My Name Here");
I suggest to try to use above solution its work for me .
I had faced the same issue and this worked for me.
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(""My Name Here"");
Related
First, I need to acknowledge the clearly very similar but not duplicate issue here. None of the proposed solutions in that thread work.
My application file structure is as follows:
app
java
[mydomain].[myapplication]
Models
DataModel.java
MainActivity.java
res
layout
activity_main.xml
content_main.xml
my_inner_layout.xml
My app build.gradle contains
dataBinding {
enabled = true
}
In MainActivity.java I have
import [mydomain].[myapplication].Models.DataModel;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemsSelectedListener {
DataModel dataModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
... <other layout creation template code> ...
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
dataModel = new DataModel();
binding.setValues(dataModel);
}
<navigation and auto-generated methods>
}
My my_inner_layout.xml contains
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="values"
type="[mydomain].[myapplication].Models.DataModel" />
</data>
<android.support.constraint.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
>
<TextView
android:id="#+id/intro_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:text="#{values.valueOne}"/>
<TextView
android:id="#+id/buying_recommendation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/intro_text"
app:layout_constraintTop_toBottomOf="#id/intro_text"
android:text="#{values.valueTwo}"/>
</android.support.constraint.ConstraintLayout>
</layout>
I am passing bind:values="#{values}" through from activity_main to its included app_bar_main to its content_main to its my_inner_layout with that same <data> value in each. Android Studio is telling me "namespace 'bind' is not bound".
If I try to run this, I get "Compilation failed; see the compiler error output for details." Looking in the build output, I see:
In text, the errors are variously error: cannot find symbol class Models and error: package Models does not exist
If I move DataModel.java out of the Models package and directly in to [mydomain].[myapplication], then I get a different result. It does build and run in the emulator, but with much of the layout information failing to appear. No hamburger menu in the top left, no title text in the header, and no settings button in the top right values previously automatically included by the autogenerated code in Android Studio. I am unable to set the title in code using setTitle, either.
Swiping from the left does bring in the navigation drawer however.
I have tried invalidating caches and restarting, cleaning, rebuilding both with the model file in Models and separately.
What I want, chiefly, is to be able to use the project structure I want. To put my models classes in a models sub-package. Once that is complete, I want to make sure the full layout information comes through, including the hamburger menu icon, settings icon, and title. How can I achieve this?
Okay, I realised where the "class Models does not exist" thing comes from. I don't know whether to blame my own stupidity or the stupidly nitpicky way this binding is implemented on Android. The package needed to be called models with a lower case "m", not Models. The binding auto-name-conversion thing must have thought Models was a class, not a package.
To fix the layout, the onCreate method had to be changed to
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
dataModel = new DataModel();
cycleInformationBinding.setRecommendation(dataModel);
// set toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Drawer layout setting
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
Specifically, things had to happen in the order:
setContentView to the main activity
Set up the data model binding
Layout concerns like drawer and toolbar.
Any other order would cause either the model binding to fail or the toolbar to not display correctly.
Just convert your existing layouts to data binding layouts (Don't forget to add variable in your xml with your activity mentioned in type)
Example:
<variable name="navdrawer" type="com.example.sampleapp.HomeScreenActivity" />
This will generate a data binding class for NavigationHeaderView in this format(May differ) NavHeaderYourActivityName.
When you bind your parent activity, you will use that binding instance to get DrawerLayout and your NavigationView, respectively.
A sample code to reduce the boilerplate for initializing views in your code:
NavHeaderHomeScreenBinding navHeaderHomeScreenBinding =
DataBindingUtil.setContentView(this, R.layout.nav_header_home_screen);
AppBarHomeScreenBinding appBarHomeScreenBinding =
DataBindingUtil.setContentView(this, R.layout.app_bar_home_screen);
ActionBarDrawerToggle toggle =
new ActionBarDrawerToggle(this, binding.drawerLayout, appBarHomeScreenBinding.toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
binding.drawerLayout.addDrawerListener(toggle);
toggle.syncState();
binding.navView.setNavigationItemSelectedListener(this);
I hope this helps someone! Thank you!
First try to remove redurant setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
Second add to end of "onCreate" function
binding.included.setValues(dataModel);
binding.executePendingBindings();
if you use include than you may add to your include id for example
<include
android:id="#+id/included"
layout="#layout/content_main"
app:values="#{DataModel}"/>
and use
binding.included.setValues(dataModel);
research about using databinding with included layouts
I have put an image from my drawable folder and added it onto my action bar and would now like to move it left over beside the back arrow. Anyone any ideas on how to do this in Android Studio. Thanks
My Code is as fallows
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setLogo(R.drawable.mainlogo);
Try using a Toolbar, the new way to make AppBars. It is more easily customized and reused, among other advantages.
Android's docs make it seem a lot harder than it really is. They use Toolbar but connect it to the AppBar API's still. If you use a lot of ActionBar utility methods like ActionBar.hide(), then it makes sense to call
setSupportActionBar(myToolbar);
But it can actually be significantly easier.
Why you don't need to setSupportActionBar
According to the article above, if we don't use the AppBar API's we don't need the custom theme, onCreateOptionsMenu(), or any of the AppBar mess.
Here is how to do Toolbars simply:
Get v7 appcompat
I think it is neccessary still to make your Activity extend AppCompatActivity
Add the following code:
At to the top of your layout resource file, inside the top level Layout of course:
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
</android.support.v7.widget.Toolbar>
In your activity:
protected void onCreate(Bundle savedInstanceState) {
...
//Get the toolbar
Toolbar toolbar = ((Toolbar)findViewById(R.id.my_toolbar));
//Set up the toolbar's navigation icon and behavior
toolbar.setNavigationIcon(R.drawable.ic_close_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//whatever you want to happen on click
}
});
}
Optionally you can do things like:
toolbar.inflateMenu(R.menu.save_menu);
toolbar.setTitle("Hey");
Heres where the custom behavior you wanted comes in. If you want an ImageView in the toolbar, you simply add it to the layout resource:
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/my_logo"/>
</android.support.v7.widget.Toolbar>
In fact, if you want a title with custom styles, instead of banging your head against the wall trying to figure out Toolbar styling, simply add a TextView where the ImageView is. You can modify that however you want, and make it your title!
https://developer.android.com/training/basics/firstapp/building-ui.html#Weight
I am doing the tutorial above and to get it to build I had to comment out these lines inside MainActivity.java inside src folder (This code is in the MainActivity class inside OnCreate()).
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
//
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
If I do not comment out these lines, I get 'cannot find' errors and can't build, example:
error: cannot find symbol variable toolbar
Can someone explain in plain english why this is happening and how I can fix it? I have tried various import.R fixes that people found to combat Eclipse randomly adding that, but they don't work. My imports:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
I am using Android Studio like the tutorial says and get the same error on a clean install. Is it my automatically generated imports? Is the tutorial wrong or incompatible with the latest Android Studio? Are my build settings wrong?
The R class is auto-generated based on what is in your *.xml files, whether they are strings, dimensions, colors, ids within layouts, etc.
When you are calling code like this:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
You are saying, "Set the toolbar variable to the widget with an id of toolbar".
In an xml, say you had three textviews like this:
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text_view_1" />
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text_view_2" />
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text_view_3" />
When I build the project, my R.java file will then be updated to have references in java code to those ids that I defined in xml, like this:
public static final int text_view_1=0x7f0c0066;
public static final int text_view_2=0x7f0c0067;
public static final int text_view_3=0x7f0c0068;
To explain it at a very basic level, the R.java file is java code that is generated to reference xml elements within actual java code.
I am guessing that when you created a project in Android Studio, it came with the MainActivity.java class. That's where that code is coming from that you posted above. The part right above that in the default MainActivity.java class is
setContentView(R.layout.activity_main);
This is setting the activity's view to the xml layout file defined in activity_main.xml. Inside of this layout is the following
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/AppTheme.AppBarOverlay"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
My guess is that perhaps your activity_main.xml does not contain this definition for the Toolbar and the FloatingActionButton widget.
If you want to really start from scratch so that you can follow the tutorial you linked, you should delete the MainActivity.java and just go create your own.
I know this is old, but I'm going to answer because this tutorial is still the best for android studios, and it poorly explains this part.
OnCreate() creates the elements you define in XML in Java, by creating the default activity, you still have a
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
and a
fab.setOnClickListener(new View.OnClickListener()
defined in OnCreate, android studios as not created these resources in android.R because you deleted there definitions in XML as part of the tutorial!
Run>Clean and Rerun'app' or ctrl+F5 on Android Studio
Disclaimer: It's build with CLI only tools, so certainly some "auto-generated lines" are missing
It's a small application with a MainActivity with a EditText and a Button
It works fine, but if I extends now from ActionBarActivity now my EditText and Button are hidden behind the Action Bar
https://developer.android.com/guide/topics/ui/actionbar.html The android documentation does not state about changes needing to be made in the layout.xml nor does the Training guide from which my application is based on
My MainActivity.java
public class MainActivity extends ActionBarActivity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// adding these lines show that the widget are correctly added
//ActionBar actionBar = getSupportActionBar();
//actionBar.hide();
}
}
My main layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="#+id/enter_verb"
android:hint="#string/enter_verb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:text="#string/button_conjugate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
My guess would be that I need to add something in my layout to make it aware there's a Action Bar, but I can't find anywhere what it should be.
Very strange, I've added the line coming from this link
https://developer.android.com/training/basics/actionbar/overlaying.html
Which is:
android:paddingTop="?attr/actionBarSize"
in my LinearLayout tag, and then recompiled, after that the widget were shown but with a padding of the size of the actionBar in addition to the actionBar itself.
I then removed the line, recompiled and it now works as expected
A bug because of temporary files?
I'm having troubles trying to style my tabs in android.
I want to make them look exactly the same as whats in the open source android contacts list (see https://android.googlesource.com/platform/packages/apps/Contacts
).
Problem is that when they display on the screen it looks a bit different to the contacts app.
When it should look like this:
Notice how the background colors are a little bit different and the text colors are different.
Not sure why this is the case as its basically the same code and icons.
My tab layout code is the following:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0dp">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0dp" />
</LinearLayout>
</TabHost>
Which doesn't contain anything special there.. and the TabActivity is as follows:
public class TabbedActivity extends TabActivity implements
TabHost.OnTabChangeListener {
private TabHost tabHost;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tab);
tabHost = getTabHost();
tabHost.setOnTabChangedListener(this);
setupLatestTab();
setupSavedTab();
tabHost.setCurrentTab(0);
}
private void setupLatestTab() {
Intent intent = new Intent().setClass(this, ResultsActivity.class);
tabHost.addTab(tabHost
.newTabSpec("latest")
.setIndicator("Latest",
getResources().getDrawable(R.drawable.ic_tab_recent))
.setContent(intent));
}
private void setupSavedTab() {
Intent intent = new Intent().setClass(this, ResultsActivity.class);
tabHost.addTab(tabHost
.newTabSpec("saved")
.setIndicator("Saved",
getResources().getDrawable(R.drawable.ic_tab_starred))
.setContent(intent));
}
#Override
public void onTabChanged(String tabId) {
// Because we're using Activities as our tab children, we trigger
// onWindowFocusChanged() to let them know when they're active. This may
// seem to duplicate the purpose of onResume(), but it's needed because
// onResume() can't reliably check if a keyguard is active.
Activity activity = getLocalActivityManager().getActivity(tabId);
if (activity != null) {
activity.onWindowFocusChanged(true);
}
}
}
I am using the same images from the drawable folders too.
I know i can set the background of tabs manually by doing something like this in the tabactivity
tabHost.getTabWidget().getChildAt(index).setBackgroundColor(Color.parseColor("#ff202020"));
But the contacts app isn't doing this sort of thing anywhere (most of the top tab code is in DialtactsActivity), so just want to do what the open source app is doing when displaying tabs - i'm not sure how and why the contacts application tabs look much better when im basically using the same code and resources.
I guess im just missing something trivial??
This turned out to be a problem with my minimum android version not being specified ..
Added:
<uses-sdk android:minSdkVersion="8" />
to the androidmanifest and it worked fine. I guess it was reverting to the old tabs look and feel in earlier versions of android.