【发布时间】:2017-01-06 20:34:44
【问题描述】:
我正在尝试更改我的片段布局中的 TextView,但是无论如何调用 findViewById 时我都会得到空值。 这是我的片段布局:
<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
【问题讨论】:
标签: java android android-fragments nullpointerexception