Ham*_*ehi 27 android toolbar direction right-to-left android-actionbar
如何将整个应用布局方向更改为RTL?我正在编写一个应用程序,用户必须在首次启动时选择它的语言,并且布局应根据用户选择更改为RTL或保持LTR.我用来添加android:supportsRtl="true"
到AndroidManifest
与android:layoutDirection="rtl"
每个布局,但这种方法有像下面一些问题:
一个问题是当我将方向更改为RTL时,ActionBar
主页图标或导航按钮(当启用了主页时)仍然是LRT并且只是向右移动.
我也试图以编程方式改变方向,结果是一样的:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
getWindows().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
Run Code Online (Sandbox Code Playgroud)
有没有办法强制所有活动一次成为RTL,或者我们应该分别在每项活动中设定方向?
Afs*_*hin 45
在应用程序的minSdk> = 17时,您可以使用这段代码.
我用fa
了Farsi
,你可以使用其他的RTL语言.
Configuration configuration = getResources().getConfiguration();
configuration.setLayoutDirection(new Locale("fa"));
getResources().updateConfiguration(configuration, getResources().getDisplayMetrics());
Run Code Online (Sandbox Code Playgroud)
改变整个布局
LinearLayout linrtl=(LinearLayout)findViewById(R.id.linrtl);
linrtl.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
Run Code Online (Sandbox Code Playgroud)
如果要更改应用程序中的语言并更改活动布局上的视图和资源的方向,请尝试以下代码:
// set Persian language in the app
setLanguage(context, "fa");
public void setLanguage(Context c, String lang) {
Locale localeNew = new Locale(lang);
Locale.setDefault(localeNew);
Resources res = c.getResources();
Configuration newConfig = new Configuration(res.getConfiguration());
newConfig.locale = localeNew;
newConfig.setLayoutDirection(localeNew);
res.updateConfiguration(newConfig, res.getDisplayMetrics());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
newConfig.setLocale(localeNew);
c.createConfigurationContext(newConfig);
}
}
Run Code Online (Sandbox Code Playgroud)
同样,更改语言后,您需要更改活动布局上已创建视图的方向。您可以使用以下代码执行此操作:
if (TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()) == ViewCompat.LAYOUT_DIRECTION_RTL) {
view.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
} else {
view.setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
}
Run Code Online (Sandbox Code Playgroud)
最简单和最好的方法
是转到app/res/values/styles
并将以下代码添加到<style>
标记,例如您在 android 清单中定义其名称的标记:
<style name"YourMainThemeName" parent="Parent Theme Of Your Choice">
<item name="android:layoutDirection">rtl</item>
<item name="windowActionBar">false</item>
</style>
Run Code Online (Sandbox Code Playgroud)
现在转到并将app/manifests/AndroidManifest.xml
以下行代码添加到<application>
标记:
<application
android:supportsRtl="true"
android:theme="@style/YourMainThemeName">
</application>
Run Code Online (Sandbox Code Playgroud)
现在您的布局方向是 rtl 并使用Toolbar
代替ActionBar
并在工具栏中定义 arrowBack 的图标
后退按钮保持 LTR 模式,因为它只有一种资源,即指向左侧的箭头。您需要指定一个新的资源文件夹,例如drawable-ldrtl-hdpi,并将指向该文件夹的相同图标放入其中。
归档时间: |
|
查看次数: |
16144 次 |
最近记录: |