在片段中调用findViewById会返回null

时间:2017-01-06 20:34:45

标签: java android android-fragments nullpointerexception

我正在尝试在片段布局中更改TextView,但是无论如何调用findViewById时我都会获得null值。 这是我的片段布局:

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.kubacm.myweather.ShowMeWeather">

    <TextView
        android:id="@+id/city_field"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="@android:color/white" />
</RelativeLayout>

从主要活动中调用片段:

@Override public void showWeather(JSONObject data){
        Bundle bundle = new Bundle();
        bundle.putString("data",data.toString());
        ShowMeWeather wf = new ShowMeWeather();
        wf.setArguments(bundle);
        getSupportFragmentManager().beginTransaction().replace(R.id.activity_main,wf).addToBackStack(null).commit();
    }

并在片段中:

public class ShowMeWeather extends Fragment {
    Typeface weatherFont;
    TextView cityField;

 public ShowMeWeather() {
        // Required empty public constructor
    }

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_show_me_weather, container, false);
        cityField = (TextView)rootView.findViewById(R.id.city_field);
        return rootView;
    }

@Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        weatherFont = Typeface.createFromAsset(getActivity().getAssets(),"fonts/weather.ttf");

        renderWeather();
    }

    public void renderWeather(){
        try{
            cityField.setText("Here should go my text");
        }catch (Exception e){
            Log.e("Simple Weather","there was an errror");
        }
    }
}

我尝试在Android Studio中清理和重建我的项目,并在尝试使用cityField.SetText时仍然保持NullPointerException

2 个答案:

答案 0 :(得分:1)

onCreateView方法之后调用

onCreate方法,因此cityField尚未初始化

答案 1 :(得分:0)

在此检查片段生命周期here onCreateView完成后调用renderWeather方法