-2
我想在代碼中動態添加一個TextView小部件,但它總是崩潰中的setText()行:嘗試添加一個TextView動態
TextView tv = new TextView(MainActivity.this);
tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
tv.setText("YOU: " + ET_message.getText().toString()); //this line crashes
ll = (LinearLayout) findViewById(R.id.LL);
ll.addView(tv);
有誰知道爲什麼嗎?這應該是最簡單的線路。
編輯:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.guy_sh.messenger.MainActivity.onClick(MainActivity.java:30)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24697)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
編輯#2:更改代碼
if(!TextUtils.isEmpty(ET_message.getText())) {
TextView tv = new TextView(MainActivity.this);
tv.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
tv.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
tv.setText("YOU: " + ET_message.getText().toString());
ll = (LinearLayout) findViewById(R.id.LL);
ll.addView(tv);
}
什麼是'ET_message'也發佈了'Crash Log' –
ET_messsage是我從中獲取文本的EditText。我不知道如何獲得崩潰日誌。 –
檢查你的logcat ...也許你的ET_message是空的? – Yoni