我的 findViewByid 在扩展片段上变成红色,我在 onCreate 方法上而不是在

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 KEY

private 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

@Override

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

return v;

}




@Override

public 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 方法上执行此操作


牛魔王的故事
浏览 1289回答 3
3回答

Helenr

片段没有findViewById()方法,所以它是红色的,因为它不存在。findViewById() 必须在 View 对象上或从 Activity(它只是该 Activity 的根 View 的代理)调用。无论如何,您也不能调用FragmentfindViewById()的onCreate()方法,因为onCreate()在之前执行onCreateView(),这意味着 Fragment 的视图此时为空。v 似乎也不是您的 Fragment 中的变量。将您的代码移至onCreateView()或onViewCreated()并findViewById()在您的视图上进行调用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java