Reputation: 1526
I'm trying to make my linearLayout scrollable programmatically but it doesnt work. Im just new in android so pls be nice 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
Upvotes: 1
Views: 504
Reputation: 21773
The issue is btn1 = ((Button) findViewById(id_));
This should look like 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
(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)
Edit
The solution in your case is simply to remove this line compeltely: btn1 = ((Button) findViewById(id_));
Upvotes: 1