我想将以编程方式创建的 View 添加到 ScrollView
中,并且该 ScrollView
是在 XML 文件中声明的。如何实现这一目标?
package com.example.multipleviews;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;
public class MainView extends Activity {
LinearLayout main, child;
ScrollView sc;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
main = (LinearLayout) findViewById(R.id.main);
// Toast.makeText(getApplicationContext(), "hello", 0).show();
view();
}
private void view() {
// TODO Auto-generated method stub
main.removeAllViews();
sc = (ScrollView) findViewById(R.id.sc);
sc.removeAllViews();
child = (LinearLayout) findViewById(R.id.lin);
child.removeAllViews();
for (int i = 0; i < 5; i++) {
Button b = new Button(this);
b.setText("Button "+i);
b.setId(i);
child=(LinearLayout)findViewById(R.id.lin);
child.addView(b);
}
sc.addView(child);
main.addView(sc);
setContentView(main);
}
}
这是我的代码......但应用程序不运行......
最佳答案
第1步:在ScrollView
中添加任意布局容器(例如线性布局)
<ScrollView android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:id="@+id/resultContentHolder"
android:layout_width="fill_parent"
android:orientation="vertical"
android:gravity="center_horizontal|top"
android:layout_height="fill_parent" />
</ScrollView>
第 2 步:在 Activity 类的布局容器中添加任何自定义 View ,例如
LinearLayout gapH = new LinearLayout(this);
LayoutParams gapParamsH = new LayoutParams(LayoutParams.FILL_PARENT,10);
gapH.setLayoutParams(gapParamsH);
resultContentHolder.addView(gapH);
关于java - 在 ScrollView 中以编程方式创建 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22678056/