序言
在移動開發中,適配問題是重中之重,特別是在閱讀類專案中,在空間有限的情況下,需要盡可能的顯示重要性高的內容,為此我自定義了一個layout,可以實作對內容權重的設定,當layout空間不足的時候,優先顯示優先級高的內容,使用方法也很簡單,和普通的layout一樣
屬性
| 名稱 | 型別 | 說明 |
|---|---|---|
| layout_order_index | int | 顯示的優先級 默認為1 ,數字越大,優先級越高,越先顯示 |
| layout_ellipses_min_size | int | 壓縮模式為縮略號時,最小的最正文字數(不包括省略號本身),如果小于這個字數則隱藏文字 |
| layout_compress_mode | 列舉 | hide:隱藏模式,如果layout剩余的空間不足則自動隱藏控制元件,通過設定TextView的visible屬性實作, ellipses:空間不足的時候,會自動在末尾添加省略號,使文本的長度剛好適配layout的剩余寬度, |
使用效果
比如下面的效果,時間和來源使用的就是OrderLayout, 時間的優先級比來源高,來源的壓縮模式為縮略號,在不同螢屏寬度的情況下,來源顯示的字數也不一樣,但是可以完美的使用螢屏剩余的空間


說明
該layout繼承自LinerLayout
- 目前只適用于TextView作為子類的情況,
- 省略號是通過動態設定TextView的內容實作的,不需要再在xml中單獨設定TextView的其他屬性,
- TextView的內容會被Layout動態設定,如果要獲取未修改的內容可以通過TRSOrderLayout的這個方法實作,
/**
* 獲取textView最原始的內容,
* @param textView
* @return
*/
public String getOriginContent(View textView) {
return contentMap.get(textView);
}
- 因為layout是通過設定TextView的visible屬性來實作隱藏和顯示的,如果你要手動的隱藏控制元件需要呼叫layout的相關方法
public void hideView(View view) {
hideViewSet.add(view);
requestLayout();
}
public void showView(View view) {
hideViewSet.remove(view);
requestLayout();
}
也可以使用如下的方法來通用設定view的顯示和隱藏
private void hideView(View view) {
if (view == null) {
return;
}
ViewParent viewParent = view.getParent();
if (viewParent instanceof TRSOrderLayout) {
TRSOrderLayout orderLayout = (TRSOrderLayout) viewParent;
orderLayout.hideView(view);
} else {
view.setVisibility(View.GONE);
}
}
private void showView(View view) {
if (view == null) {
return;
}
ViewParent viewParent = view.getParent();
if (viewParent instanceof TRSOrderLayout) {
TRSOrderLayout orderLayout = (TRSOrderLayout) viewParent;
orderLayout.showView(view);
} else {
view.setVisibility(View.VISIBLE);
}
}
Demo
大家可以下載demo,查看各種屬性的作用,通過放大和縮小按鈕,來控制OrderLayout的寬度,
代碼
<com.example.orderlayoutdemo.view.TRSOrderLayout
android:id="@+id/layout_order"
android:layout_width="250dp"
android:layout_height="30dp"
android:layout_centerInParent="true"
android:background="#aaa"
android:orientation="horizontal"
>
<TextView
android:id="@+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="我是時間"
android:textColor="#f00"
app:layout_compress_mode="hide"
app:layout_ellipses_min_size="2"
app:layout_order_index="1" />
<TextView
android:id="@+id/tv_tag"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:text="我是標簽222"
android:textColor="#0f0"
app:layout_compress_mode="ellipses"
app:layout_ellipses_min_size="2"
app:layout_order_index="2" />
<TextView
android:id="@+id/tv_source"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:text="我是來源111222333"
android:textColor="#000"
app:layout_compress_mode="hide"
app:layout_ellipses_min_size="2"
app:layout_order_index="3" />
</com.example.orderlayoutdemo.view.TRSOrderLayout>
修改引數以后記得點擊設定哦,

Demo下載

原始碼下載
原始碼地址
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/236622.html
標籤:其他
下一篇:Harmony OS 打包
