본문 바로가기
모바일개발(Mobile Dev)/안드로이드개발(Android)

how to use listview with onItemClick Event

by 테크한스 2016. 11. 13.
반응형

how to use listview 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical" 
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
    
   <ListView 
      android:id="@+id/listView1" 
      android:layout_height="fill_parent"
      android:layout_width="fill_parent" />


</LinearLayout>


public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ListView listView1 = (ListView) findViewById(R.id.listView1);
        
        Product[] items = { 
            new Product(1, "Milk", 21.50), 
            new Product(2, "Butter", 15.99), 
            new Product(3, "Yogurt", 14.90), 
            new Product(4, "Toothpaste", 7.99), 
            new Product(5, "Ice Cream", 10.00), 
        };
        
        
ArrayAdapter<Product> adapter = new ArrayAdapter<Product>(this,
                    android.R.layout.simple_list_item_1, items);
        
        listView1.setAdapter(adapter);

        listView1.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                
                String item = ((TextView)view).getText().toString();
                
                Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
                
            }
        });


    }
}

반응형