Error in Android Studio

1

I am developing an application in Android Studio but at the time of executing it by the emulator I am getting the following error:

  

Error: can not find symbol variable fab

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();
    }
});
    
asked by FABIAN AGUILAR 11.03.2017 в 14:53
source

3 answers

2

Your problem is that you do not define the variable, you should do something like this:

// Aquí debes definir la variable, así:
FloatingActionButton fab1;

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

    fab1 = (FloatingActionButton) findViewById(R.id.fab);

    fab1.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();
        }
    });

And in your layout :

   <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        fab:fab_label="Nombre"
        fab:fab_size="mini"
        android:clickable="false" />
    
answered by 11.03.2017 в 15:26
1

As UserNameYo says, you must declare your control variable. Also, I agree that you need to add your import well. I recommend you the following way:

  • Add the following line in your .gradle file in Android Studio in the dependencies part.
  • compile 'com.android.support:design:25.1.0'
    
  • By the time you add this line at the top of the code in the file, a yellow line will appear and on your right a link that will say Sync Now . Your project will be synchronized, wait for it to end.

  • Finally you add the following in Layout :

  • <android.support.design.widget.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:clickable="true"
        app:srcCompat="@android:drawable/ic_menu_add"/>
    
        
    answered by 11.03.2017 в 17:23
    0

    Also before running your application you can see the error:

    The problem is that within the layout that you load by means of setContentView() that is generally activity_main.xml , there is no element with id fab . Secure these by loading the container layout.

    Add it so you can find a reference of FloatingActionButton .

        
    answered by 22.05.2017 в 20:42