如何创建两个TextView,它们指向图表上的第一个和最后一个点?

时间:2018-03-01 13:51:27

标签: android canvas android-canvas mpandroidchart

我在我的应用中使用MPAndroidChart绘制图表。但是我遇到了一个问题。我不知道如何绘制这两个TextView,指向图表上的第一个和最后一个点。有谁知道如何做到这一点?

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用标记视图来实现此目的:

首先在项目中添加java类CustomMarkerView并在其中写下代码。

package maniac.professionalchartsfree.Utilities;

import android.content.Context;
import android.widget.TextView;

import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;

import maniac.professionalchartsfree.R;

/**
 * Created by saad.rafique on 1/5/2018.
*/

public class CustomMarkerView extends MarkerView
{
private TextView tvContent;

public CustomMarkerView(Context context, int layoutResource, int valueSize, int valueColor)
{
    super(context, layoutResource);
    // this markerview only displays a textview
    tvContent = findViewById(R.id.tvContent);
    tvContent.setTextSize(valueSize);
    tvContent.setTextColor(valueColor);
}

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

@Override
public void refreshContent(Entry e, Highlight highlight)
{
    tvContent.setText("x: " + e.getX() + "\n" +"y: " + e.getY()); // set the entry-value as the display text
}

}

之后,在layout文件夹中创建一个custom_marker.xml文件,并在其中写下以下代码。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="75dp"
android:layout_height="75dp"
android:background="@drawable/markers_bg"
>

<TextView
    android:id="@+id/tvContent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:paddingBottom="15dp"
    android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>

在您创建图表的活动中添加方法之后:

public CustomMarkerView markerView(Context context)
{
    CustomMarkerView mv = new CustomMarkerView(context, R.layout.custom_marker, 16, Color.WHITE);
    mv.setOffset(- mv.getWidth() / 2, -mv.getHeight()-25);
    return mv;
}

之后添加以下行:

    lineChart.setDrawMarkers(true);
    lineChart.setMarker(markerView(context));

现在运行您的项目,当您点击折线图的点时,您将得到您想要的结果。

现在,您必须通过将这些值设置为标记视图来手动为您的第一个和最后一个点设置此标记视图,以便标记视图保持不变,而不会单击该标记。