-1

I've started working on a menu for my app and I'm trying to start an activity from a fragment. My fragment code looks like this;

public class Studies extends Fragment {
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getActivity().setTitle("Studies");
    }

    public void goToAttract(View v) {
        Intent intent = new Intent(getActivity(), informaticainfo.class);
        startActivity(intent);
    }

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

I've got this working in a different project so I do not think that is the problem, my XML button to go to the next activity looks like this;

<Button
    android:id="@+id/I"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_marginStart="0dp"
    android:layout_marginLeft="0dp"
    android:layout_marginTop="40dp"
    android:background="@drawable/buttonshape"
    android:onClick="goToAttract" <---- is this wrong? 
    android:paddingLeft="130sp"
    android:paddingRight="130sp"
    android:text="@string/informatica"
    android:textColor="#ffffff" />

I've declared the new activity in the Manifest, but the XML file keeps giving this error at the line specified above;

Cannot resolve symbol 'goToAttract' less Inspection info: Checks if the method specified in onClick XML attribute is declared in related activity.

Does the method I'm using above not work with fragments? Why can it not find the function I have working in another project?

daan
  • 9
  • 2

2 Answers2

0

Declaring and assigning value to onClickin XML does not work in fragment, use OnClickListener programmatically instead of using onClick in XML.

TaQuangTu
  • 2,155
  • 2
  • 16
  • 30
0

Check this link [How exactly does the android:onClick XML attribute differ from setOnClickListener? According to this that with the XML above, Android will look for the onClick method only in the current Activity. This is important to remember if you are using fragments, since even if you add the XML above using a fragment, Android will not look for the onClick method in the .java file of the fragment used to add the XML.

hyhashemi
  • 43
  • 4
  • I had to put the function in the activity, not the fragment, its fixed now, thanks. – daan May 05 '19 at 12:22