find view by id标记为红色,我不是在onCreateView上做的,帮我解决这种错误,我真的是android编程的新手package com.example.mymonitoring;public class MonitoringFragment extends Fragment {private static final String TAG = "STATISTICACTIVITY";private Button Temperature;private Button Humidity;private TextView t1;private TextView t2;private static TextView t3;private static final String THINGSPEAK_CHANNEL_ID = "572138";private static final String THINGSPEAK_API_KEY = "ND76MAN2CWQJG25G"; //GARBAGE KEYprivate static final String THINGSPEAK_API_KEY_STRING = "ND76MAN2CWQJG25G";/* Be sure to use the correct fields for your own app*/private static final String THINGSPEAK_FIELD1 = "field1";private static final String THINGSPEAK_FIELD2 = "field2";private static final String THINGSPEAK_FIELD3 = "field3";private static final String THINGSPEAK_UPDATE_URL = "https://api.thingspeak.com/update?";private static final String THINGSPEAK_CHANNEL_URL = "https://api.thingspeak.com/channels/";private static final String THINGSPEAK_FEEDS_LAST = "/feeds/last?";private ThingSpeakChannel tsChannel;private ThingSpeakLineChart tsChart;private LineChartView chartView;public MonitoringFragment() { // Required empty public constructor}@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {return v;}@Overridepublic void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); t1 = (TextView) findViewById(R.id.tempNumber); t2 = (TextView) findViewById(R.id.humidNumber);这是我的 xml 代码,fragment_monitoring.xml,findviewById 标记为红色,在扩展片段中的 onCreate 方法上执行此操作
3 回答
Helenr
TA贡献1780条经验 获得超3个赞
片段没有findViewById()
方法,所以它是红色的,因为它不存在。
findViewById()
必须在 View 对象上或从 Activity(它只是该 Activity 的根 View 的代理)调用。
无论如何,您也不能调用FragmentfindViewById()
的onCreate()
方法,因为onCreate()
在之前执行onCreateView()
,这意味着 Fragment 的视图此时为空。
v
似乎也不是您的 Fragment 中的变量。
将您的代码移至onCreateView()
或onViewCreated()
并findViewById()
在您的视图上进行调用。
添加回答
举报
0/150
提交
取消