ownuregame
ownuregame

Reputation: 11

No enclosing instance of the type MainActivity is accessible in scope when making button

When trying to make an android app, I encountered the error: No enclosing instance of the type MainActivity is accessible in scope on the line Toast.makeText(MainActivity.this, "Swag", Toast.LENGTH_SHORT).show();

This is my MainActivity.java:

public class MainActivity extends ActionBarActivity {
    static Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment implements View.OnClickListener {

        public PlaceholderFragment() {
        }

        @Override
        public void onClick(View v) { 
            Toast.makeText(MainActivity.this, "Swag", Toast.LENGTH_SHORT).show();
        }

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

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

Upvotes: 1

Views: 5962

Answers (1)

jpros
jpros

Reputation: 323

You must use getActivity() inside the fragment.

Be careful, if you are doing some background job, or any other async task when it return, getActivity() may be null. So every time you use it check for null.

Further information on fragments, you can use this.

Upvotes: 2

Related Questions