我想在我的ScrollView中添加多个LinearLayout,LinearLayout的数量取决于从MySQL数据库中选择的数据量。但是,似乎不能在ScrollView中添加多个LinearLayout。
原因可能是这样的:指定的孩子已经有一个父母。您必须先在孩子的父母上调用removeView()。但是我不确定真正的原因。我怎么解决这个问题?这是我在Android Studio中的编码:
String query = "select * from restaurant";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
LinearLayout data_big_layout, detail_data_layout;
TextView name, type_area, price_txt;
ImageView restaurant_img;
LinearLayout.LayoutParams restaurant_img_params, data_big_params;
while(rs.next()){
data_big_layout = new LinearLayout(this);
data_big_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
data_big_params.setMargins(0,15,0,0);
data_big_layout.setLayoutParams(data_big_params);
data_big_layout.setOrientation(LinearLayout.HORIZONTAL);
data_big_layout.setWeightSum(20);
data_big_layout.setBackgroundColor(Color.WHITE);
data_big_layout.setTag(rs.getInt(1));
detail_data_layout = new LinearLayout(this);
lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,8.0f);
detail_data_layout.setLayoutParams(lparams);
detail_data_layout.setOrientation(LinearLayout.VERTICAL);
detail_data_layout.setPadding(50,0,0,0);
lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
name = new TextView(this);
name.setLayoutParams(lparams);
name.setText(rs.getString(2));
name.setTextSize(24);
name.setTypeface(Typeface.DEFAULT_BOLD);
type_area = new TextView(this);
type_area.setLayoutParams(lparams);
type_area.setText(rs.getString(5)+"/"+rs.getString(6));
type_area.setTextSize(18);
price_txt = new TextView(this);
price_txt.setLayoutParams(lparams);
price_txt.setText(rs.getString(7));
price_txt.setTextSize(18);
detail_data_layout.addView(name);
detail_data_layout.addView(type_area);
detail_data_layout.addView(price_txt);
data_big_layout.addView(detail_data_layout);
restaurant_img = new ImageView(this);
restaurant_img_params = new LinearLayout.LayoutParams(200,
300,12.0f);
restaurant_img.setImageResource(R.drawable.test_restaurant);
restaurant_img.setPadding(0,0,50,0);
data_big_layout.addView(restaurant_img, restaurant_img_params);
Toast.makeText(getBaseContext(),"ID: "+rs.getInt(1), Toast.LENGTH_LONG).show();
data_scroll_view.addView(data_big_layout); //Cannot add data_big_layout in the next loop
z = "Search successful";
}
isSuccess = true;
stmt.close();
rs.close();
con.close();
代码 data_scroll_view.addView(data_big_layout); 仅可在while循环的第一次运行。我选择了两行数据,但是程序中的输出只能显示一个LinearLayout。我该如何解决?谢谢大家。
答案 0 :(得分:1)
答案 1 :(得分:0)
引用https://developer.android.com/reference/android/widget/ScrollView
ScrollView是“允许放置视图层次结构的视图组 在其中滚动。滚动视图可能只有一个直接子级 放在里面。
要在滚动视图中添加多个视图,请使直接子级添加一个视图组,例如LinearLayout
,然后在该LinearLayout
“内放置其他视图。
因此,与其尝试将LinearLayouts
添加到ScrollView
中,不如将一个LinearLayout
作为ScrollView's
的子元素,并向该LinearLayout
添加任何视图/布局