[英]BringToFront doesn't work inside a coordinator layout
Android Studio 2.0 Preview 4
我正在使用BringToFront
來獲取TextView
以顯示在其他控件之前。
Doc的bringToFront()表示你必須調用requestlayout
invalidate
。 我做了什么,但沒有用。
tvLevel.bringToFront();
tvLevel.requestLayout();
tvLevel.invalidate();
我在android.support.design.widget.CoordinatorLayout
使用此TextView
但是,以下代碼確實有效。 但僅支持API 21及更高版本。 但我需要支持API 16。
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tvLevel.setTranslationZ(4);
tvLevel.invalidate();
}
或者通過設置xml
屬性屬性android:translationZ("4dp")
工作。 但是,僅適用於API 21
/**
* Change the view's z order in the tree, so it's on top of other sibling
* views. This ordering change may affect layout, if the parent container
* uses an order-dependent layout scheme (e.g., LinearLayout). Prior
* to {@link android.os.Build.VERSION_CODES#KITKAT} this
* method should be followed by calls to {@link #requestLayout()} and
* {@link View#invalidate()} on the view's parent to force the parent to redraw
* with the new child ordering.
*
* @see ViewGroup#bringChildToFront(View)
*/
public void bringToFront() {
if (mParent != null) {
mParent.bringChildToFront(this);
}
}
根據這個你可能會錯過這一行:
((View)myView.getParent()).requestLayout();
它會工作,檢查出來。!
在KITKAT之前,此方法之后應該在視圖的父級上調用requestLayout()和invalidate() ,以強制父級使用新的子級排序重繪。
必須在視圖的父級上調用這些方法。 您在視圖本身上調用它們。
這應該工作。
tvLevel.bringToFront();
tvLevel.getParent().requestLayout();
tvLevel.getParent().invalidate();
bringToFront()
在android.support.design.widget.CoordinatorLayout
為我工作。 我的環境:
activity_main.xml中:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textStyle="bold"
android:textSize="20sp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"/>
</android.support.design.widget.CoordinatorLayout>
MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.textView);
textView.bringToFront();
}
以下是截圖:
使用textView.bringToFront();
沒有textView.bringToFront();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.