Fragment 中的onConfigurationChanged 在切换语言的情况下不被回调的解决办法

原文链接:http://stackoverflow.com/questions/18725396/onconfigurationchange-not-called-after-changing-locale


在Fragment依附的Activity的manifest android:configChange="" 不能只加locale (android:configChange="locale"),还需要加上layoutDirection(android:configChange="layoutDirection|locale")。具体原因猜测应该是某些语言下是需要RTL(Right to Left),所以必须加上layoutDirection 才能触发Fragment中的onConfigurationChanged()方法的回调。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果要在不重新创建 Fragment情况切换布局,可以通过 `ViewStub` 来实现。 `ViewStub` 是一个轻量级的视图,它可以被声明在布局文件但不会立即被加载。当你需要使用它时,它会被填充并替换成你指定的布局文件。 具体实现方法如下: 1. 在 Fragment 的布局文件添加 `ViewStub`。 ```xml <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"> <ViewStub android:id="@+id/stub" android:layout="@layout/layout1" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> ``` 2. 在 Fragment 定义 `ViewStub` 和两个布局文件对应的布局 ID。 ```java private ViewStub mViewStub; private View mInflatedView1; private View mInflatedView2; ``` 3. 在 `onCreateView()` 方法获取 `ViewStub` 并设置它的监听器。 ```java @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_layout, container, false); mViewStub = view.findViewById(R.id.stub); mViewStub.setOnInflateListener(new ViewStub.OnInflateListener() { @Override public void onInflate(ViewStub stub, View inflated) { if (inflated.getId() == R.id.layout1) { mInflatedView1 = inflated; } else { mInflatedView2 = inflated; } } }); return view; } ``` 4. 在需要切换布局的地方调用 `inflate()` 方法。 ```java if (mInflatedView1 == null) { mViewStub.setLayoutResource(R.layout.layout1); mInflatedView1 = mViewStub.inflate(); } else { mViewStub.setLayoutResource(R.layout.layout2); mInflatedView2 = mViewStub.inflate(); } ``` 这样就可以在同一个 Fragment 通过 `ViewStub` 来切换不同的布局文件了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值