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



我正在使用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 值?

首先在你的

项目中创建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);

最新更新