作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的应用程序仅适用于 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/
我是一名优秀的程序员,十分优秀!