文章目錄
-
- 1、Picker
- 2、簡單實作
- 3、實戰1:簡單樣式
- 4、實戰2:更多樣式
- 5、了解更多
1、Picker
##1、Picker 是什麼?
Picker提供了滑動選擇器,允許使用者從預定義範圍中進行選擇。
2、簡單實作
- 在XML中建立Picker
<Picker
ohos:id="$+id:test_picker"
ohos:height="match_content"
ohos:width="300vp"
ohos:background_element="#E1FFFF"
ohos:layout_alignment="horizontal_center"
ohos:normal_text_size="16fp"
ohos:selected_text_size="16fp"/>
- 設定Picker的取值範圍
Picker picker = (Picker) findComponentById(ResourceTable.Id_test_picker);
picker.setMinValue(0); // 設定選擇器中的最小值
picker.setMaxValue(6); // 設定選擇器中的最大值
3、實戰1:簡單樣式
- 響應選擇器變化
picker.setValueChangedListener((picker1, oldVal, newVal) -> {
// oldVal:上一次選擇的值; newVal:最新選擇的值
});
-
格式化Picker的顯示
通過Picker的setFormatter(Formatter formatter)方法,使用者可以将Picker選項中顯示的字元串修改為特定的格式。
picker.setFormatter(i -> {
String value;
switch (i) {
case 0:
value = "Mon";
break;
case 1:
value = "Tue";
break;
case 2:
value = "Wed";
break;
case 3:
value = "Thu";
break;
case 4:
value = "Fri";
break;
case 5:
value = "Sat";
break;
case 6:
value = "Sun";
break;
default:
value = "" + i;
}
return value;
});
-
設定要顯示的字元串數組
對于不直接顯示數字的元件,該方法可以設定字元串與數字一一對應。字元串數組長度必須等于取值範圍内的值總數。使用者在使用時需要注意,該方法會覆寫picker.setFormatter(Formatter formatter)方法。
4、實戰2:更多樣式
(1)設定文本樣式
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:background_element="black"
ohos:orientation="vertical">
<Picker
ohos:id="$+id:test_picker"
ohos:height="match_content"
ohos:width="300vp"
ohos:background_element="#E1FFFF"
ohos:layout_alignment="horizontal_center"
ohos:normal_text_size="16fp"
ohos:normal_text_color="#FFA500"
ohos:selected_text_size="16fp"
ohos:selected_text_color="#00FFFF"
/>
</DirectionalLayout>
Picker picker = (Picker) findComponentById(ResourceTable.Id_test_picker);
picker.setDisplayedData(new String[]{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"});
//設定文本樣式
picker.setNormalTextFont(Font.DEFAULT_BOLD);
picker.setNormalTextSize(40);
picker.setNormalTextColor(new Color(Color.getIntColor("#FFA500")));
picker.setSelectedTextFont(Font.DEFAULT_BOLD);
picker.setSelectedTextSize(40);
picker.setSelectedTextColor(new Color(Color.getIntColor("#00FFFF")));
(2) 設定所選文本的上下邊框
<Picker
...
ohos:bottom_line_element="#40E0D0"
ohos:top_line_element="#40E0D0"/>
//建立 shape 對象
ShapeElement shape = new ShapeElement();
//設定矩形
shape.setShape(ShapeElement.RECTANGLE);
//設定顔色
shape.setRgbColor(RgbColor.fromArgbInt(0xFF40E0D0));
// 單獨設定上邊框
// picker.setDisplayedLinesTopElement(shape);
// 單獨設定下邊框
// picker.setDisplayedLinesBottomElement(shape);
// 同時設定上下邊框
picker.setDisplayedLinesElements(shape, shape);
(3)設定Picker的着色器顔色
<Picker
...
ohos:shader_color="#1E90FF"/>
(4)設定Picker中所選文本邊距與普通文本邊距的比例
<Picker
...
ohos:selected_normal_text_margin_ratio="5.0">
</Picker>
(5)設定選擇輪模式
該模式是來決定Picker是否是循環顯示資料的。
<Picker
...
ohos:wheel_mode_enabled="true"/>
5、了解更多
Picker 更多詳情