我正在尝试动态地将TextView添加到我的活动中,但是当我运行应用程序时它没有显示出来。没有错误,应用程序不会崩溃,但TextView不会显示。我的java类扩展了AppCompatActivty,我注意到当我将其更改为扩展Activity时,我的代码可以正常工作,并且TextView会显示出来。我的问题是,为什么以下代码适用于Activity但不适用于AppCompatActivity?
我的java类FormActivty.java
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FormActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.activity_form);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.container);
TextView textView = new TextView(this);
textView.setText("Hello world");
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(textView);
}
}
我的XML activity_form.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/formLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/container"
android:orientation="vertical"></LinearLayout>
</LinearLayout>
答案 0 :(得分:0)
我不确定为什么会这样,但是如果我从onCreate方法中删除PersistableBundle persistentState,那么它就可以了。我的java类现在看起来像
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FormActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.container);
TextView textView = new TextView(this);
textView.setText("Hello world");
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(textView);
}
}