android虛線

一條虛線
這裏寫圖片描述
dash_line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <stroke
        android:width="1dp"
        android:color="#E5E7EA"
        android:dashGap="1dp"
        android:dashWidth="3dp" />
</shape>

虛線框
這裏寫圖片描述
rectangle_dash.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="5dp" />
    <stroke
        android:width="10dp"
        android:color="#975FB8"
        android:dashGap="2dp"
        android:dashWidth="3dp" />
    <solid android:color="#00000000" />
</shape>

爲了看出效果,width屬性設置爲10dp。
width設置虛線寬度;
dashGap設置虛線空隙寬度;
dashWidth設置虛線的實線長度;
color設置虛線顏色;
使用

android:background="@drawable/comment_dash_line"

或者

android:background="@drawable/rectangle_dash"

然而在使用的時候,會看不到效果,虛線需要在代碼中添加一行代碼。
java代碼中

view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

這樣的話,虛線就可以看見了,但是虛線框仍然不行,因爲虛線設置了高度1dp。固定的高度,虛線就可以正常顯示了。但是虛線框在使用的過程中,高度使用的是wrap_content,所以沒有顯示出來。
需要在代碼中計算出高度後,進行設置,即可。
假設給一個textView的父佈局linearLayout設置背景虛線框,需要進行對textView的高度監測。

ViewTreeObserver vto = textView.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                int h = textView.getHeight();

                ViewGroup.LayoutParams lp = linearLayout.getLayoutParams();
                lp.height = h + i;
                linearLayout.setLayoutParams(lp);
            }
        });

其中i的值可以隨意設置,這個是設置距離textView的距離,就是padding的大小。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章