Android Fragments 如何使用横向和纵向布局?

s4n0splo  于 2023-10-19  发布在  Android
关注(0)|答案(2)|浏览(187)

我有一个Activity和几个片段(它们被称为fragmentA和fragmentB)。现在fragmentA需要有纵向和横向布局。fragmentB必须保持肖像。Activity在onCreate方法中显示fragmentA。我尝试了这个链接:https://stackoverflow.com/a/53864286/15351040在fragmentA中添加了以下代码。

override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        activity?.let {
            it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
        }
        return super.onCreateView(inflater, container, savedInstanceState)
    }
override fun onDestroyView() {
        super.onDestroyView()
        activity?.let {
            it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
        }
    }

并在fragmentB中添加了以下代码。

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    activity?.let {
        it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    }
    return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onDestroyView() {
    super.onDestroyView()
    activity?.let {
        it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
    }
}

但是当我打开fragmentB时,fragmentA再次打开,而不是fragmentB。当activity的requestOrientation被改变时,可能会调用它的onCreate。当fragmentA是肖像时,它工作得很好,但不是风景。
我现在该怎么办?

s6fujrry

s6fujrry1#

  • 使用此代码,我希望此代码可用 *
public class MainActivity extends AppCompatActivity {

@SuppressLint("SourceLockedOrientationActivity")
@Override
protected void onCreate(Bundle savedInstanceState) {
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC)){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}}
  • 和属性在清单文件中提供,所有屏幕 *
android:screenOrientation="fullSensor"
        android:windowSoftInputMode="adjustResize|stateHidden"
vom3gejh

vom3gejh2#

为AndroidManifest.xml中的Activity添加带有方向值的“修改”标签。举例来说:

<activity
            android:name=".ui.activity.MainActivity"
            android:configChanges="keyboardHidden|orientation|screenSize|screenLayout" />

相关问题