制作按钮时,范围内无法访问MainActivity类型的封闭实例

时间:2014-05-11 03:38:45

标签: java android android-button

在尝试制作Android应用时,我遇到了错误: No enclosing instance of the type MainActivity is accessible in scope就行了 Toast.makeText(MainActivity.this, "Swag", Toast.LENGTH_SHORT).show();

这是我的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;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您必须在片段中使用getActivity()。

请注意,如果您正在执行某些后台作业,或者在返回时执行任何其他异步任务,则getActivity()可能为null。所以每次使用它都要检查null。

有关片段的更多信息,您可以使用this