我正在使用 ScrollView 来显示用户添加到他的购物车中的所有产品。我创建了一个滚动视图,并在其中创建了一个线性布局“实习生”。然后,我在循环中构建每一行。这是 XML
<ScrollView
android:id="@+id/scroll"
android:layout_width="300dp"
android:layout_height="230dp"
android:layout_marginLeft="10dp" >
<LinearLayout
android:id="@+id/intern"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"></LinearLayout>
</ScrollView>
这是Java代码。
for(Carrello cns : carrello){
LinearLayout prodotto = new LinearLayout(context);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(/**/LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
prodotto.setLayoutParams(lp);
//Product name
TextView nome_p = new TextView(context);
nome_p.setWidth(dpToPx(115));
nome_p.setTextColor(getResources().getColor(R.color.grey));
nome_p.setText(cns.getNomeProdotto()); /**/
//Counts
TextView quantita = new TextView(context);
quantita.setWidth(dpToPx(80));
quantita.setGravity(Gravity.CENTER);
quantita.setTextColor(getResources().getColor(R.color.grey));
quantita.setTextAppearance(context, R.style.quantita);
quantita.setText(cns.getQuantita());
//Price
TextView prezzo = new TextView(context);
prezzo.setWidth(dpToPx(70));
prezzo.setPadding(dpToPx(5), 0, 0, 0);
prezzo.setTextColor(getResources().getColor(R.color.grey));
prezzo.setTextAppearance(context, R.style.prezzo);
prezzo.setText("€"+cns.getCosto());
//Cancella
Button canc = new Button(context);
LinearLayout.LayoutParams lp_btn = new LinearLayout.LayoutParams(/*LinearLayout.LayoutParams.WRAP_CONTENT*/40,40/*LinearLayout.LayoutParams.WRAP_CONTENT*/);
lp_btn.setMargins(0, dpToPx(10), 0, 0);
canc.setLayoutParams(lp_btn);
canc.setBackground(getResources().getDrawable(R.drawable.btn_canc));
canc.setId(Integer.parseInt(cns.getIDprodotto()));/**/
Log.d("ID-CANC",String.valueOf(canc.getId()));
//create the line
prodotto.addView(nome_p);
prodotto.addView(quantita);
prodotto.addView(prezzo);
prodotto.addView(canc);
intern.addView(prodotto);
i++;
}//end for
然后,添加intern
到滚动视图:
scroll.addView(intern);
但是当我运行模拟器时,logCat 说“ScrollView 只能托管一个直接的孩子”,并且应用程序崩溃了。