FAB + NullPointerException Button

0

I suppose it's a simple problem, but I can not see the solution. I created a Floating Button (FAB) in a Fragment on Android, and when I try to configure the ClickListener, I get a NullPointer error. Here are the codes:

xml:

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right|end"
        android:layout_margin="16dp"
        android:clickable="true"/>

MainActivity.java

FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         Intent criar = new Intent(MainActivity.this, Fragment1.class);
         startActivity(criar);
     }
}

The error message says that the code tries to call the setOnClickListener method on a null object.

Any tips are welcome. Thanks.

    
asked by anonymous 01.03.2016 / 18:21

1 answer

0

I have now verified in your question that you have declared FloatingActionButton in your Fragment. That way you can not use findViewById () directly from your MainActivity , and that's why it's getting null.

Take a look at documentation : / p>

  

Finds a view that was identified by the XML attribute that was processed in onCreate (Bundle).

That is, using% direct% of its findViewById() , the function will look for this MainActivity within the FloatingActionButton that is connected to its layout and not its MainActivity .

To solve the problem, you simply instantiate this Fragment within your FloatingActionButton and set your click event in there, or you move that Fragment to the layout of your FloatingActionButton .

    
01.03.2016 / 18:41