William William - 9 days ago 7
Android Question

Android app dynamically created buttons appearing all in the same place

I'm working on my first android app and have run into some trouble. I'm trying to start a new activity which takes in an ArrayList from the previous activity and creates a button for each item in the list. I've tried looking at many other stack overflow posts but none of them have helped solve my problem.

I have tried many different strategies, and my code is currently as below:

public class VideoMenu extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_menu);
Bundle b = getIntent().getExtras();

ArrayList<String> videos = b.getStringArrayList("videos");

setContentView(R.layout.activity_video_menu);

for(int i=0;i<videos.size();i++){
Button myButton = new Button(this);
myButton.setText(videos.get(i));
myButton.setId(i);

RelativeLayout ll = (RelativeLayout)findViewById(R.id.videos);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (i != 0) {
lp.addRule(RelativeLayout.END_OF, i - 1);
}
myButton.setLayoutParams(lp);

ll.addView(myButton,lp);
}

}


}

and XML code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/videos"
android:layout_alignParentBottom="true"
android:layout_alignWithParentIfMissing="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical">




This compiles just fine, but all of the buttons appear on top of one another. If you could include reasons for why any code suggestions might work I would appreciate it. I'd like to learn more about this :)

Edit: fixed typo

Answer

The reason is that you are adding the buttons to a RelativeLayout. RelativeLayout basically add all views to wherever you specify in the view. You're not really specifying, so they're all appearing on top of each other.

In order to fix this, change your RelativeLayout to a LinearLayout, with orientation of either horizontal or vertical. horizontal will add views side by side in a horizontal line, and vertical will add them in a vertical line.