Reputation: 33
i'm trying to create buttons dynamically though code using a linear layout to set one button after the other, my code runs doesn't give any errors, nor throwing any exceptions or anything, but all i get is an empty screen. Thanks in advance.
private void runThreadCreateButton(final List<Stop> stops) {
new Thread() {
public void run() {
int i=0;
while (i++ < 1) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
for(int j=0;j<stops.size();j++)
{
Button myButton = new Button(getApplicationContext());
myButton.setText(stops.get(j).getName());
LinearLayout ll = new LinearLayout(getApplicationContext());
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
}
}
});
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}.start();
}
Upvotes: 0
Views: 98
Reputation: 1120
Well, if you didn't add your layout to your activity this was your main problem.
However you should learn about composing your layouts in xml. This makes your code a lot more readable and maintainable. Also you don't need to worry about switching Threads all the time.
If you need to populate your views with runtime data, you should use list views and list adapters. ListViews and ListAdapters are essentials to almost every android app, so you you should really learn about them. If you want your list items to hold more complex layout you can do so by implementing your own custom list adapters.
There are also lots of performance tweaks you can do, when using list views. For most use cases generating and managing your layout from code is not a good approach.
Upvotes: 1
Reputation: 20142
you create a new Layout, but you Activity is not set to show your layout. Call setContentView()
on your Main Activity with your new layout.
LinearLayout ll = new LinearLayout(getApplicationContext());
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
//add something like this
yourMainActivity.setContentView(ll);
Upvotes: 1