Skip to article frontmatterSkip to article content

Udacity: Android Basics

Cornell University

User Interface

Images & Texts

View Groups

Linear Layout

Relative Layout

Multiscreen Apps

Add texts to the Layout

with List

ArrayList<String> words;

//findViewById only returns a View, we should downcast it to a LinearLayout
LinearLayout rootView = (LinearLayout) findViewById(R.id.rootView);

for(String word:words){
    //TextView takes into a context, in this case is "this"
    TextView wordView = new TextView(this);
    wordView.setText(word);
    
    //add wordView to the this View of List(LinearLayout)
    rootView.addView(wordView);
}

However, a LinearLayout is not scrollable and can easily go beyond the screen. Therefore, we should use an ArrayAdapter

with ArrayAdapter

ArrayAdapter<Word> itemsAdapter = new WordAdapter(this, words);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(itemsAdapter);

We have to create two more classes: a Word class, and a customized WordAdapter that extends ArrayAdapter<Word>. We also have to create another XML file to customize the display of one item in the list.