我想创建一个应用程序,用户在开始时选择纵向或横向模式,然后使用该模式。从游戏开始,用户可以在他/她开始新游戏时进行更改。我写了以下测试代码:
公共类MainActivity扩展了Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Button landscape = new Button(this);
Button portrait = new Button(this);
landscape.setText("LandScape");
landscape.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setupLandscape();
}
});
portrait.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setupPortrait();
}
});
portrait.setText("Portrait");
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
ll.addView(landscape);
ll.addView(portrait);
setContentView(ll);
}
public void setupLandscape(){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
ll.setBackgroundColor(Color.rgb(255,0,0));
setContentView(ll);
}
public void setupPortrait(){
Toast t = Toast.makeText(this,"Portrait",Toast.LENGTH_SHORT);
t.show();
}
}
然而,当我按下横向按钮时,没有任何反应。布局不会重置为其他内容。那么我做错了什么?有什么办法可以做我想要的吗?