find view by id標(biāo)記為紅色,我不是在onCreateView上做的,幫我解決這種錯(cuò)誤,我真的是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 標(biāo)記為紅色,在擴(kuò)展片段中的 onCreate 方法上執(zhí)行此操作
3 回答

Helenr
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊
片段沒(méi)有findViewById()
方法,所以它是紅色的,因?yàn)樗淮嬖凇?/p>
findViewById()
必須在 View 對(duì)象上或從 Activity(它只是該 Activity 的根 View 的代理)調(diào)用。
無(wú)論如何,您也不能調(diào)用FragmentfindViewById()
的onCreate()
方法,因?yàn)?code>onCreate()在之前執(zhí)行onCreateView()
,這意味著 Fragment 的視圖此時(shí)為空。
v
似乎也不是您的 Fragment 中的變量。
將您的代碼移至onCreateView()
或onViewCreated()
并findViewById()
在您的視圖上進(jìn)行調(diào)用。
添加回答
舉報(bào)
0/150
提交
取消