Firerazzer
Firerazzer

Reputation: 192

Show a label when a value is selected [MPAndroidChart]

I want to show a label with specific data when a value is selected like in the demo-Image of what I want:

Image of the I want

so I paste this code (found in the source of the exemple):

protected RectF mOnValueSelectedRectF = new RectF();

@Override
public void onValueSelected(Entry e, Highlight h) {

    if (e == null)
        return;

    RectF bounds = mOnValueSelectedRectF;
    mChart.getBarBounds((BarEntry) e, bounds);
    MPPointF position = mChart.getPosition(e, AxisDependency.LEFT);

    Log.i("bounds", bounds.toString());
    Log.i("position", position.toString());

    Log.i("x-index",
            "low: " + mChart.getLowestVisibleX() + ", high: "
                    + mChart.getHighestVisibleX());

    MPPointF.recycleInstance(position);
}

but it doesn't work, the log are displayed but nothing happen on the screen. What I have forget or miss

Upvotes: 3

Views: 5244

Answers (3)

FawwazFaisal
FawwazFaisal

Reputation: 77

Here is an easier solution:

Step 1: We do not need to show values over the bars so:

binding.barchart.setDrawValueAboveBar(false)

Step 2: To enable values to show on bars (assuming there is only 1 barDataset in DataSet):

binding.barchart.data.dataSets[0].setDrawValues(true)
binding.barchart.data.dataSets[0].valueTextColor = ContextCompat.getColor(requireContext(),android.R.color.transparent)

This will make the values appear invisibly on bars initially

Step 3:

barchart.setTouchEnabled(true)
barchart.setOnChartValueSelectedListener(object : OnChartValueSelectedListener{
            override fun onValueSelected(e: Entry?, h: Highlight?) {
                if(selectedEntry!=e){
                    barchart.data.dataSets[0].setValueTextColors(getValColors(e!!.x))
                }
            }

            override fun onNothingSelected() {
                barchart.data.dataSets[0].valueTextColor = ContextCompat.getColor(requireContext(),android.R.color.transparent)
            }

        })

private fun getValColors(xAxis: Float):ArrayList<Int>{
        return arrayListOf<Int>().apply {
            for(i in 0 until(23)){
                if(xAxis.toInt()==i){
                    add(ContextCompat.getColor(requireContext(),android.R.color.white))
                }else{
                    add(ContextCompat.getColor(requireContext(),android.R.color.transparent))
                }
            }
        }
    }

Upvotes: 0

Firerazzer
Firerazzer

Reputation: 192

To display a marker with something inside when a value is selected we have to use a MarkerView and not the valueSelected listener.

All the necessary doc for create yours is here : https://github.com/PhilJay/MPAndroidChart/wiki/IMarker-Interface

Upvotes: 5

Mehul Kabaria
Mehul Kabaria

Reputation: 6622

Have you written below the line in your code?

mChart.setOnChartValueSelectedListener(this);

Upvotes: 1

Related Questions