diogobernardino / williamchart

Android Library to rapidly develop attractive and insightful charts in android applications.
5.1k stars 800 forks source link

Provide a way to let tooltips draw values #298

Open joel-apollo opened 3 years ago

joel-apollo commented 3 years ago

Using the code below, I almost had nice tooltips per bar, something like this: almost tooltips

That is, till I realized the x and y aren't the actual values, just scaled values etc. Can we pass tooltips the x,y values or pair of the point being drawn?

@ExperimentalFeature
class TextToolTip(
    val textSize: Float = 16f,
    @ColorRes val textColor: Int? = null,
    val typeface: Int = Typeface.NORMAL,
    val pixelsAboveBar: Float = 8f,
    val labelsFormatter: ((Float) -> String)?) : Tooltip {

    private lateinit var tooltipView: TextView

    override fun onCreateTooltip(parentView: ViewGroup) {
        tooltipView = TextView(parentView.context)
        tooltipView.layoutParams = ViewGroup.LayoutParams(wrapContent, wrapContent)
        tooltipView.visibility = View.INVISIBLE
        tooltipView.textSize = textSize
        textColor?.let { tooltipView.textColor = ContextCompat.getColor(parentView.context, it) }
        tooltipView.setTypeface(tooltipView.typeface, typeface)
        parentView.addView(tooltipView)
    }

    override fun onDataPointTouch(x: Float, y: Float) {
        tooltipView.visibility = View.VISIBLE
        tooltipView.x = x - tooltipView.width / 2
        tooltipView.y = y - tooltipView.context.dips(pixelsAboveBar)
        tooltipView.text = labelsFormatter?.let { it(y) } ?: y.toString()
    }

    override fun onDataPointClick(x: Float, y: Float) {}

}

fun Context.dips(dipValue: Float) =
    TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, resources.displayMetrics)
diogobernardino commented 3 years ago

That is, till I realized the x and y aren't the actual values, just scaled values etc.

x and y are the chart view coordinates of a given point.

Can we pass tooltips the x,y values or pair of the point being drawn?

Passing the index of the pair might be enough to fulfill this use-case. With that I was able to reach something close to what you need I believe. I will consider it for the next release.

image