简体   繁体   English

以编程方式以线性布局滚动视图

[英]Scrollview in a linear layout programmatically

I'm trying to make my linearLayout scrollable programmatically but it doesnt work. 我正在尝试以编程方式使我的linearLayout可滚动,但是它不起作用。 Im just new in android so pls be nice tnx!.. 我是android的新手,所以tnx不错!

full code 完整的代码

  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);

Error stack trace 错误堆栈跟踪 在此处输入图片说明

The issue is btn1 = ((Button) findViewById(id_)); 问题是btn1 = ((Button) findViewById(id_));

This should look like btn1 = (Button) findViewById(R.id.whatever_your_id_is_in_xml); 看起来应该像btn1 = (Button) findViewById(R.id.whatever_your_id_is_in_xml);

Because you don't supply an id it never finds your button, so btn1 is null when you try to set the listener 由于您不提供ID,因此它永远找不到您的按钮,因此当您尝试设置监听器时,btn1为null

(find view is looking in the xml / root view for this id, you dont need to do this - you already have the button because you created it programmatically) (查找视图正在xml /根视图中查找此ID,您不需要这样做-因为已经以编程方式创建了该按钮,所以已经有了该按钮)

Edit 编辑

The solution in your case is simply to remove this line compeltely: btn1 = ((Button) findViewById(id_)); 您的情况的解决方案是简单地btn1 = ((Button) findViewById(id_));删除此行: btn1 = ((Button) findViewById(id_));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM