gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:52:40 24 4
gpt4 key购买 nike

我的应用程序仅适用于 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com