在MPAndroidChart饼图/条形图中显示单击切片/条的Y值

时间:2018-03-13 18:09:01

标签: android mpandroidchart

我正在使用MPAndroidChart库在我的应用程序中显示一些图形(饼图和条形图)。 除非用户点击切片/条,否则我不希望条形和切片有任何文字说明。然后,只显示此精确切片/条的描述。

现在我得到了某种解决方法,一旦用户点击切片/条,就会显示/取消显示所有Y值:

sessionsPieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {

                sessionsPieChart.setUsePercentValues(true);
                pieDataSet.setValueTextSize(12);
            }

            @Override
            public void onNothingSelected() {

                sessionsPieChart.setUsePercentValues(false);
                pieDataSet.setValueTextSize(0);
            }
        });

如何只显示点击的切片/条的Y值?

1 个答案:

答案 0 :(得分:1)

首先在项目中创建MyMarkerView.java类:

public class MyMarkerView extends MarkerView {

private TextView tvContent;

public MyMarkerView(Context context, int layoutResource) {
    super(context, layoutResource);
    // this markerview only displays a textview
    tvContent = (TextView) findViewById(R.id.tvContent);
}

// callbacks everytime the MarkerView is redrawn, can be used to update the
// content (user-interface)

@Override
public void refreshContent(Entry e, Highlight highlight)
{
    // here you can change whatever you want to show in following line as x/y or both
    tvContent.setText("x: " + e.getX() + " , y: " + e.getY()); // set the entry-value as the display text
}

}

之后创建以下布局文件custom_marker.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="40dp"
android:background="@color/colorPrimary"
>

<TextView
    android:id="@+id/tvContent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:text=""
    android:textSize="12dp"
    android:textColor="@android:color/black"
    android:ellipsize="end"
    android:singleLine="true"
    android:textAppearance="?android:attr/textAppearanceSmall" />

 </RelativeLayout>

在您创建图表之后,添加以下代码:

   MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker);
   combinedChart.setMarker(mv);