Toolbar disappears when I add another widget in activity

1

I created a Toolbar for MainActivity, as shown below:

However,whenIaddanyotherwidgetinthesameactivity,thetoolbardisappearswhenIruntheemulator:

Hasanyoneeverhadthesameproblemorknowhowtosolveit?

Codetoolbar.xml:

<?xmlversion="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
android:id="@+id/toolbar"
xmlns:android="http://schemas.android.com/apk/res/android" />

Code menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:icon="@drawable/ic_add_circle_outline_black_24dp"
    android:title="Adicionar outro item"
    android:id="@+id/adicionarItem"
    app:showAsAction="always"
    />
<item
    android:icon="@drawable/ic_save_black_24dp"
    android:title="Salvar lista"
    android:id="@+id/salvarLista"
    app:showAsAction="always"
    />
</menu>

Activity_main.xml code (without adding another widget):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context="lucaspereira.listadecompras.MainActivity">

<include
    layout="@layout/toolbar"/>
</RelativeLayout>

MainActivity.java code:

...
public class MainActivity extends AppCompatActivity {

private Toolbar toolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

}
public boolean onCreateOptionsMenu (Menu menu){
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}
public boolean onOptionsItemSelected(MenuItem menuItem){
    switch (menuItem.getItemId()){
        case R.id.adicionarItem:

            break;
        case R.id.salvarLista:

            break;
    }
    return true;
}
}
    
asked by anonymous 01.07.2017 / 02:12

1 answer

0

The error occurs when id of your <include> is different findViewById(R.id.toolbar); . In your case it is android:id="@+id/include" . Here's an example below:

<include
    android:id="@+id/toolbar"
    layout="@layout/toolbar"/>

In class:

toolbar = (Toolbar)findViewById(R.id.toolbar);

And for any other view to be below, you need to set property of android:layout_below by referencing the id of your <include> . See:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/include"
    android:text="Caraca funfou!" />
    
01.07.2017 / 03:05