【问题标题】:how to make scrollview without xml?如何在没有 xml 的情况下制作滚动视图?
【发布时间】:2021-08-29 05:30:28
【问题描述】:

我有这样的代码:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val linearLayout:LinearLayout = LinearLayout(this)

        linearLayout.orientation = LinearLayout.VERTICAL

        setContentView(linearLayout)

            for (i in 0 until 35){
            val button = Button(this)
            button.text = "Button ${i+1}"
                linearLayout.addView(button)


            }
        }


        }

如何制作滚动视图? google了半天也没找到信息

【问题讨论】:

  • 为什么你可以在没有 xml 的情况下让你的活动可以滚动?

标签: android xml kotlin android-activity


【解决方案1】:

您正在向 LinerLayout 添加按钮,因此它不可滚动。
首先你必须声明一个滚动视图
val scrollView = ScrollView(this),
然后像这样将 LinerLayout 添加到滚动视图
scrollView.addView(linearLayout),
然后将该 ScrollView 用于 setContentView()

【讨论】:

    【解决方案2】:

    创建类型为 ScrollView 的视图组对象并将单个根子对象添加到它,这在您的情况下是线性布局。

        val scrollView: ScrollView = ScrollView(this)
        scrollView.isFillViewport = true
        val linearLayout: LinearLayout = LinearLayout(this)
    
        linearLayout.orientation = LinearLayout.VERTICAL
        scrollView.addView(linearLayout)
        setContentView(scrollView)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-08
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多