创建FrameLayout后,我想将TextView添加到特定的位置。但是当我尝试添加查看应用程序崩溃时。怎么了?
我的代码:
float metrics;
TextView text, text2;
FrameLayout screen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (FrameLayout)findViewById(R.id.screen);
DisplayMetrics metrics = getResources().getDisplayMetrics();
text = (TextView)findViewById(R.id.text);
text.setText(""+metrics + "\n"+metrics.widthPixels + "\n"+ metrics.heightPixels);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(100, 100);
text.setText("XXX");
screen.addView(text2, 100, 100);
这里是我的XML代码:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/a"
android:orientation="vertical"
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=".MainActivity" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</FrameLayout>
logcat(只有红色部分):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{eu.eurohardware24.tictactoe/eu.eurohardware24.tictactoe.MainActivity}:
java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1997)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2018)
at android.app.ActivityThread.access$500(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1124)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:152)
at android.app.ActivityThread.main(ActivityThread.java:4636)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:491)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.view.ViewGroup.addViewInner(ViewGroup.java:3303)
at android.view.ViewGroup.addView(ViewGroup.java:3193)
at android.view.ViewGroup.addView(ViewGroup.java:3163)
at eu.eurohardware24.tictactoe.MainActivity.onCreate(MainActivity.java:28)
at android.app.Activity.performCreate(Activity.java:4521)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1961)
... 11 more
答案 0 :(得分:1)
您的应用崩溃了,因为您没有在任何地方初始化text2
。
也许您打算创建一个新的TextView
:
text2 = new TextView(this);