144,767 views 227 on YTPak
741 16

Published on 24 Mar 2013 | over 3 years ago

Demonstration on how to create a simple list view and populate it with text elements. Full Java code below.

package ca.demo.demolistview;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

// Array of options --} ArrayAdapter --} ListView
// List view: {views: da_items.xml}

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

populateListView();
registerClickCallback();
}


private void populateListView() {
// Create list of items
String[] myItems = {"Blue", "Green", "Purple", "Red"};

// Build Adapter
// TODO: CHANGE THE [[ to a less than, ]] to greater than.
ArrayAdapter[[String]] adapter = new ArrayAdapter[[String]](
this, // Context for the activity.
R.layout.da_item, // Layout to use (create)
myItems); // Items to be displayed

// Configure the list view.
ListView list = (ListView) findViewById(R.id.listViewMain);
list.setAdapter(adapter);
}

private void registerClickCallback() {
ListView list = (ListView) findViewById(R.id.listViewMain);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
// TODO: CHANGE THE [[ to a less than, ]] to greater than.
public void onItemClick(AdapterView[[?]] paret, View viewClicked, int position, long id) {
TextView textView = (TextView) viewClicked;
String message = "You clicked # " + position
+ ", which is string: " + textView.getText().toString();
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
});
}
}

Loading related videos...