IDK
IDK

Reputation: 445

Code issue Android Studio

I'm trying to run an app but while compiling I get this errors:

MainFragment.java:62: error: <identifier> expected
newButton.setOnClickListener(new View.OnClickListener() 
                           ^ 
MainFragment.java:62: error: illegal start of type
newButton.setOnClickListener(new View.OnClickListener() 
                            ^
MainFragment.java:62: error: ')' expected
newButton.setOnClickListener(new View.OnClickListener() 
                               ^    
MainFragment.java:62: error: ';' expected
newButton.setOnClickListener(new View.OnClickListener() 
                                    ^
MainFragment.java:62: error: invalid method declaration; return type      required
newButton.setOnClickListener(new View.OnClickListener() 
                                     ^

This is my code:

View newButton = rootView.findViewById(R.id.new_button);

newButton.setOnClickListener(new View.OnClickListener()
{
   @Override
   public void onClick(View view)
   {
      Intent intent = new Intent(getActivity(), GameActivity.class);
      getActivity().startActivity(intent);
   }

});

I don't understand the problem, what is wrong with my code?

Upvotes: 0

Views: 79

Answers (3)

Horrorgoogle
Horrorgoogle

Reputation: 7868

Can you please try this:

            Button btn = (Button) rootView.findViewById(R.id.new_button);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                  //Do whatever you want
                Intent intent = new Intent(getActivity(), GameActivity.class);
                getActivity().startActivity(intent);
                }
            });

or simple you can try by implementing OnClickListener:

  public class YourFragment extends Fragment implements OnClickListener{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.your_fragment, container, false);
    Button btn = (Button) rootView.findViewById(R.id.new_button);
    btn.setOnClickListener(this);
 return rootView;
}

@Override
   public void onClick(View v) {
    switch (v.getId()) {
    case R.id.new_button:

       //
  Intent intent = new Intent(getActivity(), GameActivity.class);
  getActivity().startActivity(intent);

        break;
    }
}

Hope this will help to solve your issue.

Upvotes: 2

Greggz
Greggz

Reputation: 1799

Change your reference type to button. The class View only provides the method onclickListener, by herself she doesn't have an implementation of it.

Button newButton = (Button) rootView.findViewById(R.id.new_button);

Upvotes: 0

Santanu Sur
Santanu Sur

Reputation: 11477

Check your braces and check wether you have returned the rootview properly.Please post you full ~onCreateView() ~ of you fragment

Upvotes: 1

Related Questions