如何以编程方式创建Scrollview?

时间:2012-03-27 10:33:03

标签: android database scrollview

我有一个表“TABLE_SUBJECT”,其中包含许多主题。我需要创建
一个水平滚动视图与主题。

如何以编程方式创建包含数据库项的ScrollView?如果我输入1o主题,那么它将作为按钮显示在滚动视图中。有可能吗?

5 个答案:

答案 0 :(得分:22)

您可以按以下方式创建:

ScrollView scroll = new ScrollView(context);
scroll.setBackgroundColor(android.R.color.transparent);
scroll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                                             LayoutParams.FILL_PARENT));
scroll.addView(yourTableView);

答案 1 :(得分:4)

如果您首先需要包含许多元素,则需要在Scroll视图中进行总结和添加;例如,我需要在scrollview中有很多文本视图,所以你需要创建ScrollView-> LinearLayout->很多textview

                ScrollView scrollView = new ScrollView(context);
                scrollView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

                TextView textView = new TextView(context);
                textView.setText("my text");

                LinearLayout linearLayout = new LinearLayout(context);
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                linearLayout.setGravity(Gravity.RIGHT);
                linearLayout.addView(textView);
                scrollView.addView(linearLayout);

答案 2 :(得分:3)

这可能对你有帮助。

    HorizontalScrollView hsrll = (HorizontalScrollView)findViewById(R.id.hrsll);

    b = new Button(this);

    for (int i = 0; i < 5; i++) {

        b.setWidth(LayoutParams.WRAP_CONTENT);
        b.setHeight(LayoutParams.WRAP_CONTENT);

        b.setText("b"+i);
        b.setId(100+i);

        hsrll.addView(b);
    }

而不是for循环只需根据需要修改代码(db中没有记录)。但这是动态创建按钮的代码。

答案 3 :(得分:2)

我是这样做的:

  • 在ScrollView
  • 中使用LinearLayout创建xml
  • 在ScrollView中创建xml作为项目
  • 在活动中使用ScrollView将主要内容设置为xml
  • 遍历所有表格元素并添加新的View to LinearLayout表单主视图

对我来说工作正常。

答案 4 :(得分:0)

在Kotlin中,您可以使用以下代码

    val scroll = ScrollView(context)
    scroll.setBackgroundColor(R.color.transparent)
    scroll.layoutParams = LayoutParams(
        LayoutParams.FILL_PARENT,
        LayoutParams.FILL_PARENT
    )
    scroll.addView(yourTableView)
相关问题