Android 将项目添加到LinearLayout(并调整大小)
我有下面的布局Android 将项目添加到LinearLayout(并调整大小),android,Android,我有下面的布局 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#f00"
android:id="@+id/main_layout">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#0f0"
android:id="@+id/bed_list"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00f"
android:text="Howdy cowboy?"
android:textSize="50dip"
android:textColor="#fff"
android:id="@+id/textview"/>
</LinearLayout>
我想在R.id.bed_列表中添加一些文本视图(就好像它们是垂直选项卡一样)
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
这个.setContentView(R.layout.main);
LinearLayout床位列表=(LinearLayout)findViewById(R.id.bed_列表);
对于(int i=0;i<12;i++){
System.out.println(“在循环中”);
TextView TextView=新的TextView(此);
setText(“HJM-”+i);
textView.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
textView.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
bedList.addView(textView,i,
新建LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_内容,
LinearLayout.LayoutParams.WRAP_内容);
}
}
到目前为止,代码已经运行,循环中的System.out.println消息出现在控制台上,但我只看到textview(R.id.textview
)。我希望列表显示在屏幕左侧,并计算选项,但它不起作用
进一步说,如果我在标签中定义了第一个textview(这样在最开始时就有一些项目,并且保留了一个空间),我可以看到该textview,但其他(从程序中添加的)也不会出现。您的textview(R.id.textview)的宽度为
匹配父视图
,有效地推送了其他视图(线性布局)屏幕外。相反,你可以给它一个宽度为wrap\u content
,可能给它一个layout\u weight
。好的,我想“match\u parent”在HTML中会像“*”一样工作,不会覆盖其他视图“wrap\u content”。无论如何,我以编程方式添加的视图仍然不会显示出来。不,“match\u parents”使视图占用所有可能的空间。您还可以尝试使用addChild(textView,i)而不使用layoutparams,尤其是不使用setWidth()和setHeight()的它尝试将宽度/高度设置为0或WRAP_内容常量的任何值。您可以通过这种方式设置layoutparams宽度和高度,但不能设置视图。好的,您是对的。但是现在项目不会填充床单
线性布局。任何简单的方法(固定/程序计算的宽度除外)因此,我可以使列表展开,并使所有项目匹配\u parent
。如果不匹配,我可能会切换到GridViewTry,使用您首先使用的addChild()方法,但宽度为match\u parent。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
LinearLayout bedList = (LinearLayout) findViewById(R.id.bed_list);
for (int i = 0; i < 12; i++) {
System.out.println("In the loop");
TextView textView = new TextView(this);
textView.setText("HJM-" + i);
textView.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
textView.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
bedList.addView(textView,i,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
}
}