我想在我的片段佈局中更改TextView,但是,無論如何,在調用findViewById時,我都會得到空值。 這裏是我的片段佈局:在片段中調用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