java - Android:代码仅适用于 onCreateOptionsMenu,不适用于 OnCreate

标签 java android eclipse

我的应用程序仅适用于 onCreateOptionsMenu(Menu menu)方法但不在 OnCreate() 中.

为什么?

这里是:

public class MainActivity extends ActionBarActivity {


Button button2;

TextView joke;

Random ran = new Random();


@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);

    button2 = (Button) findViewById(R.id.b2);

    joke = (TextView) findViewById(R.id.joke);



    button2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            StringBuilder sb = new StringBuilder();

            ArrayList<Integer> al = new ArrayList<Integer>();
            for(int i = 1; i <= 49; i++)
                al.add(i);

            for(int i = 0; i < 6; i++) {
                int y = al.remove(ran.nextInt(al.size()) );
                sb.append("  " + y + "  ");

            }

            joke.setText(sb);
        }
    });

    return true;
}



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

    public PlaceholderFragment() {
    }

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

} 

所以尝试剪切并粘贴 onCreate() 内的代码方法...你会看到错误:(

最佳答案

您应该在onCreateView(PlaceholderFragment类)中编写代码:

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        button1 = (Button) rootView.findViewById(R.id.b1);
        //...
        return rootView;
    }

关于java - Android:代码仅适用于 onCreateOptionsMenu,不适用于 OnCreate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24105537/

相关文章:

java - Linux 上如何处理 JVM OutOfMemoryError?

java - JPA 2.0 Date Comparsin JPA查询

java - 改造 POST 请求 Multipart 和 Field

android - 截图

android - 为平板电脑设置选项卡布局 tabmode 的最佳方法是什么?

java - 哪里可以找到 javadoc

eclipse - 项目浏览器中的项目消失但仍保留在磁盘中

java - 使用 HashMap 创建文本字数统计

java - 更改 Java Swing 的背景

eclipse - 使用Gradle buildship Eclipse插件找不到调试选项