| | |
| | | // 添加一个属性定义三角形图标的点击区域扩展范围 |
| | | private val triangleClickPadding: Float = 15f * context.resources.displayMetrics.density // 20dp |
| | | |
| | | // 添加一个标识符,用于区分不同的 ExpandButton 实例 |
| | | private var buttonId: String = "default" |
| | | |
| | | companion object { |
| | | private const val PREFS_NAME = "expand_button_prefs" |
| | | private const val KEY_LEGEND_STATES = "legend_states" |
| | | } |
| | | |
| | | init { |
| | | // 保存 XML 中设置的默认字体大小 |
| | | defaultTextSize = textSize |
| | |
| | | } |
| | | |
| | | /** |
| | | * 设置按钮的唯一标识符 |
| | | * @param id 标识符 |
| | | */ |
| | | fun setButtonId(id: String) { |
| | | this.buttonId = id |
| | | // 加载保存的状态 |
| | | loadStates() |
| | | } |
| | | |
| | | /** |
| | | * 保存所有图例项的状态 |
| | | */ |
| | | private fun saveStates() { |
| | | val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) |
| | | val states = legendItems.map { it.isSelected } |
| | | prefs.edit().putString("${KEY_LEGEND_STATES}_$buttonId", states.joinToString(",")).apply() |
| | | } |
| | | |
| | | /** |
| | | * 加载保存的状态 |
| | | */ |
| | | private fun loadStates() { |
| | | val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) |
| | | val savedStates = prefs.getString("${KEY_LEGEND_STATES}_$buttonId", null) |
| | | |
| | | if (savedStates != null && legendItems.isNotEmpty()) { |
| | | val states = savedStates.split(",").map { it.toBoolean() } |
| | | states.forEachIndexed { index, state -> |
| | | if (index < legendItems.size) { |
| | | legendItems[index].isSelected = state |
| | | } |
| | | } |
| | | invalidate() |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 设置图例内容 |
| | | */ |
| | | @JvmName("setLegendsList") |
| | |
| | | unselectedIcon.setBounds(0, 0, iconSize, iconSize) |
| | | LegendItem(selectedIcon, unselectedIcon, description) |
| | | } |
| | | |
| | | // 加载保存的状态 |
| | | loadStates() |
| | | |
| | | if (!isExpanded) { |
| | | text = collapsedText |
| | |
| | | index, |
| | | legendItems[index].isSelected |
| | | ) |
| | | |
| | | // 保存状态 |
| | | saveStates() |
| | | |
| | | invalidate() |
| | | } |
| | | |