gpt4 book ai didi

android - 以编程方式在线性布局中 ScrollView

转载 作者:行者123 更新时间:2023-11-30 03:06:47 26 4
gpt4 key购买 nike

我正在尝试以编程方式使我的 linearLayout 可滚动,但它不起作用。我只是 android 的新手,所以请多多关照!..

完整代码

  ScrollView scrollView= new ScrollView(this);
LinearLayout mainLayout= new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);

for (int i = 1; i <= 20; i++) {
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setTag(i);
Button btn1 = new Button(this);
btn1.setId(i);
final int id_ = btn1.getId();
btn1.setText("button " + id_);

btn1 = ((Button) findViewById(id_));
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(),
"Button 1 clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
linearLayout.addView(btn1);
mainLayout.addView(linearLayout);


}
scrollView.addView(mainLayout);
setContentView(scrollView);

错误堆栈跟踪 enter image description here

最佳答案

问题是 btn1 = ((Button) findViewById(id_));

这应该看起来像 btn1 = (Button) findViewById(R.id.whatever_your_id_is_in_xml);

因为你不提供 id 它永远找不到你的按钮,所以当你尝试设置监听器时 btn1 为空

(查找 View 正在 xml/ Root View 中查找此 ID,您不需要这样做 - 您已经有了按钮,因为您是通过编程方式创建的)

编辑

您的解决方案是完全删除这一行:btn1 = ((Button) findViewById(id_));

关于android - 以编程方式在线性布局中 ScrollView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21677074/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com