[英]Programmatically Adding views in inflated layout
我正在嘗試以編程方式在線性布局中添加視圖,這是膨脹視圖的一部分,但是在線性布局中添加視圖后它沒有顯示
MainActivity 代碼:-
final LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.suscription_alert,null);
LinearLayout ll = view.findViewById(R.id.LinearLayout);
for(int i =0;i<4;i++) {
TextView t = new TextView(MainActivity.this);
t.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
t.setText("Hello");
ll.addView(t);
}
view.invalidate();
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.setView(view)
.create();
Objects.requireNonNull(alert.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
alert.show();
訂閱警報布局:-
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="SUBSCRIPTIONS"
android:textColor="#F5D90A"
android:textSize="23sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<LinearLayout
android:id="@+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingTop="10dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView3" />
</androidx.constraintlayout.widget.ConstraintLayout>
output:
此處未顯示以編程方式添加的視圖,如何解決此問題以及為什么會發生任何人有任何想法?
您的LinearLayout
需要具有大於 0 的高度才能在運行時添加視圖,否則它將無法計算高度。
例如讓它wrap_content
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="SUBSCRIPTIONS"
android:textColor="#F5D90A"
android:textSize="23sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<LinearLayout
android:id="@+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView3" />
</androidx.constraintlayout.widget.ConstraintLayout>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.