0
我試圖動態地添加一個TextView到我的活動,而是要動態添加的TextView當我運行它沒有顯示出來的應用程序。沒有錯誤,應用程序不會崩潰,但TextView不顯示。我的java類擴展了AppCompatActivty,並且我注意到當我將其更改爲擴展Activity時,我的代碼工作,並且TextView顯示出來。我的問題是,爲什麼下面的代碼適用於Activity而不是AppCompatActivity?無法在Java類擴展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>
看看這個:http://stackoverflow.com/questions/6216547/android-dynamically-add-views-into-view。 –