我的应用仅适用于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;
}
}
}
所以尝试Cut&amp;将代码粘贴到onCreate()
方法中...您将看到错误:(
答案 0 :(得分:1)
您应该在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;
}