简体   繁体   中英

android starting Activity from Intent in onClickListener in common class returns error

I have a navigation button that I use in each class and want to set its onClickListener in the class that contains all the common code. However I get a

"The method startActivity(Intent) is undefined for the type new View.OnClickListener(){}"

error in startActivity(i).

The relevant code is:

    public static void initiateNavigationButton(Context context, View view, int layoutResource) {
    final Context classContext = context;

    LayoutInflater inflater = LayoutInflater.from(classContext);
    View layout = inflater.inflate(layoutResource, (ViewGroup) view);

    Button navigationButton = (Button) layout.findViewById(R.id.navigation_button);

    navigationButton.setOnClickListener(new View.OnClickListener() { 
        @Override
        public void onClick(View v) { 
            Intent i = new Intent(classContext, HomeActivity.class);

            startActivity(i); 
        }
    });
    }

You are inside an inner class that implements the View.OnClickListener .

That class does not have a startActivity method that you could call, so you need to wrap it in order to access the parent activity's method. Assuming that your class' name is 'MyActivity', change the line startActivity(i); to

MyActivity.this.startActivity(i);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM