1

Having a hard time with fragments. I have a MainActivity that switches to a fragment with a flip-card animation pushing a button.

fragment.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<Button
    android:id="@+id/coin2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp"
    android:text="@string/coin_button"
    android:onClick="flipcoin2" />
</LinearLayout>

fragment class:

public class CardBackFragment extends Fragment {


    public CardBackFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_coindice, container, false);
    }

    public void flipcoin2(View view){
        //no code

    }

}

The CardBackFragment class is actually in the MainActivity.java file, not a separate file. The app starts, the flipcard animation works, I see the button in the fragment, I can switch back to the main Activity. But when I click on the coin2 button the app crashes with following exception

java.lang.IllegalStateException: Could not find a method flipcoin2(View) in the  activity class com.example.myapp.MainActivity for OnClick handler on view class android.widget.Button with id 'coin2'

I put intentionally no code in the method to see if there was something wrong into the method, but it's not the case. What's wrong?

Adi
  • 2,364
  • 1
  • 17
  • 23
glass
  • 159
  • 2
  • 12
  • check this link http://stackoverflow.com/questions/6091194/how-to-handle-button-clicks-using-the-xml-onclick-within-fragments – Sabeer Aug 20 '14 at 17:28

1 Answers1

1

This is because the MainActivity doesn't implement that method. As described in this link the tools:context attribute expects an Activity, not a Fragment. You could do that instead :

public class CardBackFragment extends Fragment implements OnClickListener
{

    public CardBackFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View v = inflater.inflate(R.layout.fragment_coindice, container, false);
        v.findViewById(R.id.coin2).setOnClickListener(this);
        return v;
    }

    public void onClick(View view){
        switch (view.getId())
        {
            case R.id.coin2:
            break;
        }
    }
}
ChristopheCVB
  • 7,269
  • 1
  • 29
  • 54