我正在尝试以编程方式设置TextView
的文本。在我的应用程序中,我正在调用一种方法,该方法会在TableRow
内部创建View
。此View
包含TextView
。现在我正在尝试使用方法setText()
更改文本。
city_layout.xml
...
<TextView
android:id="@+id/textView_City_Name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/city_name"
android:textColor="#FFFFFF"
android:textSize="35dp"
android:gravity="center_horizontal"
android:textStyle="bold"
android:paddingTop="65dp"/>
...
和我的片段类
private View createCityInList(String cityName) {
TableRow tr = new TableRow(getActivity());
View v = LayoutInflater.from(getActivity()).inflate(R.layout.city_layout, tr, false);
//change attr here!
TextView textView = (TextView) getView().findViewById(R.id.textView_City_Name);
textView.setText(cityName);
return v;
}
因此,如果我尝试在手机上运行此应用程序,只需关闭该应用程序并使用logcat给我这个
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.app.city/de.app.city.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
我不知道setText行有什么问题,有人可以告诉我吗?
也许有帮助: 在我的片段中,我指向另一个布局(fragment_layout)。但我想创建一个city_layout视图并更改textview中的文本。这个视图我想在fragment_layout中显示。
答案 0 :(得分:0)
这是您的问题
private View createCityInList(String cityName) {
TableRow tr = new TableRow(getActivity());
View v = LayoutInflater.from(getActivity()).inflate(R.layout.city_layout, tr, false);
//change attr here!
TextView textView = (TextView) getView().findViewById(R.id.textView_City_Name);
textView.setText(cityName);
return v;
}
getView()这里是null。
将其更改为:
private View createCityInList(String cityName) {
TableRow tr = new TableRow(getActivity());
View v = LayoutInflater.from(getActivity()).inflate(R.layout.city_layout, tr, false);
//change attr here!
TextView textView = (TextView) v.findViewById(R.id.textView_City_Name);
textView.setText(cityName);
return v;
}
你将会全力以赴。
答案 1 :(得分:0)
而不是
TextView textView = (TextView) getView().findViewById(R.id.textView_City_Name);
尝试
TextView textView = (TextView) v.findViewById(R.id.textView_City_Name);