转载

使用带有start和end的属性

你问Android对原生RTL(从右到左显示)资词不资词,当然是资词啦。4.2以后,Android支持原生RTL。

优点

构建更优雅的变换布局方向的用户界面,支持由右到左(RTL)的语言和阅读方向,比如阿拉伯语和希伯来语。

使用方法

  • manifest中添加android:supportsRtl=”true”声明应用支持RTL mirroring
  • 使用start/end属性代替left/right属性

有这些:paddingStart、drawableStart、layout_marginStart、layout_alignStart、layout_alignParentStart等

  • 如果兼容4.2以下还要同时加上left/right
  • 要测试可以切换到阿拉伯语等语言或者在调试模式强制开启RTL

原理

/**
* Returns the resolved layout direction for this view.
*
* @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
* {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
*
* For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
* is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
*
* @attr ref android.R.styleable#View_layoutDirection
*/

@ViewDebug.ExportedProperty(category = "layout", mapping = {
@ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
@ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
})
@ResolvedLayoutDir
public int getLayoutDirection() {
final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
if (targetSdkVersion < JELLY_BEAN_MR1) {
mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
}
return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
}

/**
* Indicates whether or not this view's layout is right-to-left. This is resolved from
* layout attribute and/or the inherited value from the parent
*
* @return true if the layout is right-to-left.
*
* @hide
*/

@ViewDebug.ExportedProperty(category = "layout")
public boolean isLayoutRtl() {
return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
}

包括View、TextView等组件都会根据以上方法的返回值来确定例如ScrollBar的位置、PaddingLeft等属性的真实值、文字的显示顺序等等,具体见各个组件的源码。

正文到此结束
Loading...