Android Chart框架 MPAndroidChart學習筆記15_標簽設置
1.自定義標記
在MPAndroid中提供了兩種方法:
- 實現
IMaker
接口類 - 繼承
MarkerView
實現MakerView類
這里我們選擇第二種方式,代碼如下:
1.1 繼承MarkerView
實現MakerView類
public class MyMarkView extends MarkerView{
private TextView tvContent;
/**
* Constructor. Sets up the MarkerView with a custom layout resource.
*
* @param context
* @param layoutResource the layout resource to use for the MarkerView
*/
public MyMarkView(Context context, int layoutResource) {
super(context, layoutResource);
tvContent= (TextView) findViewById(R.id.tv_content);
}
@Override
public void refreshContent(Entry e, Highlight highlight) {
tvContent.setTextColor(getResources().getColor(R.color.colorAccent));
tvContent.setText("您選擇的是"+e.getY());
super.refreshContent(e, highlight);
}
private MPPointF mOffset;
@Override
public MPPointF getOffset() {
if(mOffset==null){
mOffset=new MPPointF(-(getWidth()/2),-getHeight());
}
return mOffset;
}
}
1.2 實例化并引用
IMarker marker= new MyMarkView(getContext(),R.layout.makerview);
mChart.setMarker(marker);
當然我們需要一個layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@id/tv_content"/>
</LinearLayout>
1.3分析方法
在1.1的繼承類方法:
構造函數:在這里實例化對象
public MyMarkView(Context context, int layoutResource) {
super(context, layoutResource);
tvContent= (TextView) findViewById(R.id.tv_content);
}
刷新內容:這里設置標記顯示的內容
@Override
public void refreshContent(Entry e, Highlight highlight) {
tvContent.setTextColor(getResources().getColor(R.color.colorAccent));
tvContent.setText("您選擇的是"+e.getY());
super.refreshContent(e, highlight);
}
設置標簽出現位置
getWidth()、getHeight()表示標簽的寬度、高度
private MPPointF mOffset;
@Override
public MPPointF getOffset() {
if(mOffset==null){
mOffset=new MPPointF(-(getWidth()/2),-getHeight());
}
return mOffset;
}
所以這里的顯示效果如下:
new MPPointF(-(getWidth()/2),-getHeight())
如果我們嘗試設置為
mOffset=new MPPointF(0,0);
那么便會出現下面的樣式
new MPPointF(0,0)
怎么樣,察覺到不一樣了嗎?