我知道我必须使用android:screenOrientation =" portrait / landscape"如果我不想改变屏幕的旋转,但我在Manifest中这样做。我想在java类中做同样的事情。我怎么能这样做?
这是我的代码
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
switch (getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
View rootView = inflater.inflate(R.layout.fragment_cubo, container, false);
return rootView;
case 2:
View rootView2 = inflater.inflate(R.layout.fragment_cubo2, container, false);
return rootView2;
case 3:
View rootView3 = inflater.inflate(R.layout.fragment_cubo3, container, false);
return rootView3;
case 4:
View rootView4 = inflater.inflate(R.layout.fragment_cubo4, container, false);
return rootView4;
default:
View rootView0 = inflater.inflate(R.layout.fragment_cubo, container, false);
return rootView0;
}
}
我想仅在案例2和3中更改屏幕的位置,但我无法回想起方法setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
因为它无法从静态上下文中引用(onCreateView方法在类静态中)
我该怎么做?
答案 0 :(得分:0)
这样的事情:
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
关于此主题的精彩博文:https://www.novoda.com/blog/portrait-only-apps/: - )
你不应该真正更新问题,而是提出新问题。
您需要覆盖具有活动参数的回调方法,或将参数另存为字段。所以你可能需要两次运行switch语句。
@Override
public void onAttach(Activity activity) {
// your switch statement
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
您可以在此处详细阅读:https://developer.android.com/reference/android/app/Fragment.html#Lifecycle
答案 1 :(得分:0)
您可以通过以下功能
执行此操作 public void changeOrientation() {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
}
}