gpt4 book ai didi

Android 方向更改 : Different Layout, 相同的 fragment

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:58:56 25 4
gpt4 key购买 nike

这几乎是一个经典的 Android 用例。

假设我们有 2 个 fragment :FragmentA 和 FragmentB。

在横向模式下,FragmentA 和 FragmentB 并排放置。

在纵向模式下,它们在使用时各自占据全屏。

(查看此图片,但替换平板电脑->横向和手机->纵向) Different Layout, Same Fragments on Orientation Change

如此处 ( Supporting Single-Pane and Multi-Pane Layouts ) 所述,有两种方法可以实现此目的:

1- Multiple fragments, one activity: Use one activity regardless of the device size, but decide at runtime whether to combine fragments in the layout (to create a multiple-pane design) or swap fragments (to create a single-pane design).

2- Multiple fragments, multiple activities: On a tablet, place multiple fragments in one activity; on a handset, use separate activities to host each fragment. For example, when the tablet design uses two fragments in an activity, use the same activity for handsets, but supply an alternative layout that includes just the first fragment. When running on a handset and you need to switch fragments (such as when the user selects an item), start another activity that hosts the second fragment.

这在理论上很有意义,但我在尝试以在方向改变和按下后退按钮时恢复 fragment 状态的方式实际实现这些方法中的任何一种时遇到了一些障碍.

我尝试了第一种方法并取得了很大进展,但发现它很困惑,因为它需要手动管理所有 fragment 事务,特别是因为 fragment 的容器不能轻易更改。决定在 back pressed 上做什么也很痛苦,因为 backstack 上的最后一个事务可能属于另一个方向。

现在我正在尝试第二种选择。到目前为止看起来更干净了,但是每次方向更改时都会从头开始重新创建 fragment (因为每个方向使用不同的 Activity )。 我希望有一种方法可以从其他 Activity/orientation 恢复 Fragment 状态。

谁能解释一下这是如何完成的,或者给我指点一个合适的教程或示例应用程序?

最佳答案

  • MainActivity 中添加此配置,其中 Fragment 被替换 <activity android:name=".MainActivity" android:configChanges="orientation|screenSize|keyboard|keyboardHidden"
    android:label="@string/app_name">
    <intent-filter> <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.DEFAULT"/></intent-filter>
    </activity
  • 您已经为 FragmentAFragmentB 创建了 fragment 横向布局 enter image description here
  • 如果你需要改变两个 fragment 的行为你应该改变 fragment 的 onConfigurationChanged 事件。

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
//write your stuff for landscape orientation
}else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{
//write your stuff for portrait orientation
}
}

关于Android 方向更改 : Different Layout, 相同的 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30564737/

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