我正在尝试在一个片段中测试此GraphView库。 graphView = new LineGraphView(this, message);
这行有一个错误,如下所示:
无法解析构造函数LineGraphView
不确定如何引用正确的上下文。
这是该库示例演示的链接。
https://github.com/jjoe64/GraphView-Demos/blob/master/src/com/jjoe64/graphviewdemos/SimpleGraph.java
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.LineGraphView;
public class GraphFragment extends Fragment {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static final GraphFragment newInstance(String message)
{
GraphFragment f = new GraphFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String message = getArguments().getString(EXTRA_MESSAGE);
View v = inflater.inflate(R.layout.graphfragment_layout, container, false);
TextView messageTextView = (TextView)v.findViewById(R.id.textView);
messageTextView.setText(message);
GraphViewSeries exampleSeries = new GraphViewSeries(new GraphView.GraphViewData[] {
new GraphViewData(1, 2.0d)
, new GraphViewData(2, 1.5d)
, new GraphViewData(3, 2.5d)
, new GraphViewData(4, 1.0d)
});
GraphView graphView;
graphView = new LineGraphView(this, message);
graphView.addSeries(exampleSeries); // data
LinearLayout layout = (LinearLayout) v.findViewById(R.id.graph1);
layout.addView(graphView);
return v;
}
}
最佳答案
改成:
graphView = new LineGraphView(container.getContext(), message);
Activity
扩展了context
,但片段却没有,因此,只要您尝试将片段附加到布局上,它的父ViewGroup
(在其中显示片段)就会传递给onCreateView,您可以从中获取上下文。