1

I have an imageButton on my xml:

<ImageButton
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_marginTop="10dp"
    android:id="@+id/star"
    android:background="@drawable/star"
    android:layout_below="@+id/releaseDate"
    android:layout_alignLeft="@+id/releaseDate"
    android:layout_alignStart="@+id/releaseDate" />  

I want to add the action of the button, but the problem is that the imageButton I created is returning null when fetching the imagebutton on xml with findViewById:

public class DetailActivity extends AppCompatActivity {
    ImageButton ib;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        if(savedInstanceState == null){
            getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new DetailActivityFragment())
                .commit();
            ib = (ImageButton)findViewById(R.id.star);
            if(ib != null) {
                ib.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.v(null, "Image Clicked!");
                }
            });
        }
    }
}
Joao Pereira
  • 75
  • 2
  • 11
  • 1
    is the ImageButton in R.layout.activity_detail or R.id.container – WenChao Oct 25 '15 at 23:48
  • the imageButton is on fragment_detail which is called by DetailActivityFragment which is initiated by DetailActivity class – Joao Pereira Oct 25 '15 at 23:52
  • 2
    call findViewById(R.id.star) if DetailActivityFragment class, not in activity. Your fragment has not created in method onCreate – ArtKorchagin Oct 25 '15 at 23:53
  • I cannot call findViewById in the DetailActivityFragment, its not recognized – Joao Pereira Oct 26 '15 at 00:05
  • the problem was implementing the onClick on a fragment, found the solution: http://stackoverflow.com/questions/6091194/how-to-handle-button-clicks-using-the-xml-onclick-within-fragments – Joao Pereira Oct 26 '15 at 00:13

0 Answers0