在java中利用迴圈建立LinearLayout時,將其設置回水平,並且在其中增加button。
我要建立兩個LinearLayout,並分別在個別底下增加1個button
預期呈現為
按鈕11
按鈕21
實際呈現為
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_constraintTop_toBottomOf="@+id/unfold">
<LinearLayout
android:id="@+id/all"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
LinearLayout all = pop_view.findViewById(R.id.all);
LinearLayout linear[] = new LinearLayout[6];
for (int i = 1; i <= 2; i++ ){
linear[i] = new LinearLayout(MainActivity.this);
linear[i].setOrientation(LinearLayout.HORIZONTAL); //設置水平
//linear[i].setBackgroundDrawable(getResources().getDrawable(R.drawable.test));
String linearID = "linear" + i ; // 設置ID
int resID = getResources().getIdentifier(linearID, "id", getPackageName());
linear[i].setId(resID);
all.addView(linear[i]);
LinearLayout resIDc = pop_view.findViewById(resID);
ViewGroup.LayoutParams params = resIDc.getLayoutParams();
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
params.height = ViewGroup.LayoutParams.FILL_PARENT;
resIDc.setLayoutParams(params);
Button bt[] = new Button[10];
for (int j = 1; j <= 1; j++) {
bt[j] = new Button(MainActivity.this);
bt[j].setText("按鈕"+i+j);
resIDc.addView(bt[j]);
}
}