gpt4 book ai didi

android - 如何在屏幕方向改变时重新加载具有新尺寸的 fragment

转载 作者:太空狗 更新时间:2023-10-29 12:40:50 27 4
gpt4 key购买 nike

我有一个 fragment ,其中一个 TextView 从文件夹中获取它的宽度:

valuesvalues-port

当方向发生变化时,这些值也会发生变化,但 fragment 的 UI 没有任何影响。

事实上,它实际上从 values-port 和:

如果设备处于横向模式:onConfigurationChanged() 将调用新的横向方向。

如果设备处于纵向模式:不会调用 onConfigurationChanged()。

每当我改变方向时,肯定会调用 onConfigurationChanged()

所以,

为什么总是从纵向模式开始?

如何实现 UI 元素的尺寸变化效果。

我在 fragment 中尝试了这样的事情:

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getView().requestLayout();
}

但不起作用。

我的 TextView 的宽度始终来自 values-port 文件夹。

编辑:可能看起来多余,但这是代码:

<activity
android:name=".FeedActivity"
android:configChanges="orientation|screenSize|keyboardHidden"
android:screenOrientation="portrait" >
</activity>

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}

我知道我可以从 list 中删除 android:screenOrientation="portrait" 而不是 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); 在 Activity 中,但想知道此代码的行为。

最佳答案

FeedActivity 有一个固定的方向,在您的 list 中由属性 android:screenOrientation 指定。因此,当您旋转设备时它不会执行任何操作。即使可以,您也将覆盖 android:configChanges。这是the docs说:

Lists configuration changes that the activity will handle itself. When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. Instead, the activity remains running and its onConfigurationChanged() method is called.

您的 list 告诉系统 FeedActivity 将自行处理方向、屏幕尺寸和键盘配置更改。 las,您实际上并没有那样做。

既然你说你正在用 XML 加载你的 Fragment,我假设它看起来像这样:

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<fragment android:layout_width="@dimen/frag_width"
android:layout_height="match_parent"
android:tag="your_tag_here"
class="path.to.your.Fragment"/>

</FrameLayout>

要获得您期望的行为,您应该使用

更新 list
<activity
android:name=".FeedActivity"
android:configChanges="screenSize|keyboardHidden"/>

更新

如果您坚持使用 onConfigurationChanged 方法更改您的 Fragment 宽度,这可能有效:

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
final View view = getView();
if (null != view) {
view.getLayoutParams().width = getResources().getDimensionPixelSize(R.dimen.width);
}
}

不过我会反对这种方法。

关于android - 如何在屏幕方向改变时重新加载具有新尺寸的 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26355236/

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