【发布时间】:2016-09-02 16:26:02
【问题描述】:
所以我使用的是 MPAndroidChart LineCharts,这意味着在 XML 中我是这样定义的:
<com.github.mikephil.charting.charts.LineChart
android:id="@+id/line_chart"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
但是我正在尝试使用各种默认设置等来使用此图表,所以我创建了一个自定义类来尝试扩展它:
public class MyLineChart extends com.github.mikephil.charting.charts.LineChart {
private Context mContext;
public MyLineChart(Context context) {
super(context);
mContext = context;
}
//...
所以当我想在我的代码的其他地方使用它时,我有:
private MyLineChart mChart;
...
mChart = new MyLineChart(getActivity());
mChart = (MyLineChart) findViewById(R.id.line_chart);
这一切似乎都可以正常编译,但随后会引发运行时错误,因为它说我无法将 LineChart 转换为 MyLineChart。
【问题讨论】:
-
你也必须在你的 xml 中使用 MyLineChart
-
您显示的不是“包装”,而是“扩展”。并且
LineChart不能转换为MyLineChart,因为前者不是后者的子类。MyLineChart可以转换为LineChart,但反之则不行。 -
我尝试在 XML (com.mypackagename.appname.MyLineChart) 中使用 MyLineChart,但在尝试为活动布局充气时出现充气错误
-
@SashaSalauyou 我改用了extend而不是wrap
-
你能添加那个错误吗?因为那是你应该这样做的方式。顺便说一句,为什么要创建两次,第二次分配(findViewById)应该足够了。
标签: java android xml android-activity mpandroidchart