Thursday, 22 January 2015

ListView example

ListView Example in android






strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ListView</string>
   
</resources>

activity_main.xml
<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"   
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" >
    </ListView>

</RelativeLayout>

listview_xml2.xml
<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="#000000">
   
</TextView>

MainActivity.java:
package com.swamys.listview;

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

public class MainActivity extends Activity implements OnItemClickListener {

       String[] tech = { "Java", "Android", "Dot Not", "Oracle" };

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

              ListView listView = (ListView) findViewById(R.id.listView1);

              ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                           getApplicationContext(), R.layout.listview_xml2, tech);

              listView.setAdapter(adapter);
              listView.setOnItemClickListener(this);

       }

       @Override
       public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
              Toast.makeText(getApplicationContext(), "  " + tech[arg2],
                           Toast.LENGTH_LONG).show();
       }
}

No comments:

Post a Comment