2017-03-17 114 views
0

在我ScreenFragment类:为什么我尝试创建一个返回null的图表?

Activity parentActivity; 
public LineChart chart; // changing private to public didn't help 

在其onCreate()

parentActivity = getActivity(); 

在其onCreateView()

chart = (LineChart) parentActivity.findViewById(R.id.chart_id); 

这是返回null。 ID在分段的XML中定义:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:padding="@dimen/fab_margin" 
    tools:context="io.aeroscope.aeroscope.ScreenFragment"> 
    <com.github.mikephil.charting.charts.LineChart 
     android:id="@+id/chart_id" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"/> 
</FrameLayout> 

为什么null?为什么没有实例化图表?

+0

什么是你的线型图类的代码?你有一个默认的无参数构造函数吗? – pat

+0

LineChart类是MPAndroidChart包的一部分。这是我第一次尝试使用它。 –

+0

第一次尝试的一切看起来都很棒,除了沿着图表底部的网格线未被绘制。任何想法为什么? –

回答

1

基本上,您在父级活动而不是片段视图中查找视图。

应该

onCreateView() { 
View view = inflator.inflate(....); 
chart = (LineChart) view.findViewById(R.id.chart_id); 
return view; 
} 
+0

谢谢!我确定自己读过的地方是因为Views是由ID发现的,所以他们可以在任何地方被定义(并找到)。显然不是。 –