How to make items clickable in list view?
Asked Answered
D

4

8

I have been trying to search for a solution, but with very little success. I have to display a pop up window containing a list of items. I was able to display the window but onitemclicklistener is not being called upon clicking an item in the list view. Any help with this issue would be greatly appreciated.

Thanks

Edit1:

public class PopUpWindowActivity extends Activity {

    /** Called when the activity is first created. */
    String[] countries = new String[] {
        "India", "USA", "Canada"
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout ll = new LinearLayout(this);
        ListView lv = new ListView(this);
        lv.setAdapter(new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1, countries));
        lv.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView <? > arg0, View arg1, int arg2,
                    long arg3) {
                    Log.v("clicked", (String)((TextView) arg1).getText());
                }

            });
        ll.addView(lv);
        setContentView(ll);
    }
}

In the above code, i tried to create a layout inside which i added a list view. This makes the list view no longer clickable. I have to do this because, i am trying to implement a pop up window inside which there should be multiple items along with a list view.

Detect answered 7/3, 2012 at 6:10 Comment(1)
put your code.By default ListView is clickable.Pion
P
1

Edited Answer

Apply This Sample Please This Works For You I have Tested This Code

//ListviewActivity.java

 package com.anl.lk;

 public class ListviewActivity extends ListActivity { 

     static final String[] COUNTRIES = new String[] {

         "Afghanistan", "Albania", "Algeria", "American Samoa",
             "Andorra", "Angola", "Anguilla", "Antarctica",
             "Antigua and Barbuda", "Argentina", "Armenia", "Aruba",
             "Australia", "Austria", "Azerbaijan", "Bahrain",
             "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize",
             "Benin", "Bermuda", "Bhutan", "Bolivia",
             "Bosnia and Herzegovina", "Botswana", "Bouvet Island",
             "Brazil", "British Indian Ocean Territory"
     };

     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setListAdapter(new ArrayAdapter < String > (this,
                 android.R.layout.simple_list_item_1, COUNTRIES));
         getListView().setTextFilterEnabled(true);
     }

     @Override
     protected void onListItemClick(ListView l, View v, int position, long id) {
         // TODO Auto-generated method stub
         super.onListItemClick(l, v, position, id);

         new AlertDialog.Builder(this)
             .setTitle("Hello")
             .setMessage("from " + getListView().getItemAtPosition(position))
             .setPositiveButton("OK",
             new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int which) {}
             })
             .show();

         Toast.makeText(ListviewActivity.this,
             "ListView: " + l.toString() + "\n" +
             "View: " + v.toString() + "\n" +
             "position: " + String.valueOf(position) + "\n" +
             "id: " + String.valueOf(id),
             Toast.LENGTH_LONG).show();
     }

 }

//FirstPage

package com.anl.lk;

public class FirstPage extends Activity {

    @override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent sam = new Intent(FirstPage.this, ListviewActivity.class);
                    startActivity(sam);

                }
            });
    }
}

//Manifest File

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.anl.lk"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:label="@string/app_name"
        android:name=".FirstPage" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".ListviewActivity"    android:theme="@android:style/Theme.Dialog"></activity>
</application>

Please Use This Code it have your Solution

Pyrotechnic answered 7/3, 2012 at 6:14 Comment(5)
i mean for showing A pop up for an Activity we should use android:theme="@android:style/Theme.Dialog" in the manifest for the corresponding Activity so that it will Load Any Activity means even listview on that popup windowPyrotechnic
OnListItemClick will be available to override only when we extend listactivity class. But i wanted to display the list inside a popup window.Detect
please use this Code Updated And tested(Working Code)Pyrotechnic
Yes, i was able to get the solution.Detect
Downvoted this. No explanation of the code. Very non-constructive.Lymn
B
14

Is the list and items in the list set to clickable? Either programmatically...

ListView myList = (ListView) findViewById(R.id.list_view_id);
myList.setClickable(true);

Or in the XML...

   <ListView xmlns:android="http://schemas.android.com/apk/res/android"
       android:clickable="true">
   ...
   </ListView>

I assume you did that, but sometimes we miss even the obvious :)

EDIT:

From the Android Tutorial here is how to set an onItemClickListener programmatically.

 ListView lv = getListView();
 lv.setOnItemClickListener(new OnItemClickListener() {

   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
       // When clicked perform some action...
   }
 });

EDIT 2:

Here is my XML

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

    <ListView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/list" />

</LinearLayout>

And here is my code

 public class HelloAndroidActivity extends Activity {

     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         String[] countries = getResources().getStringArray(R.array.countries_array);

         ListView lv = (ListView) findViewById(R.id.list);
         lv.setAdapter(new ArrayAdapter < String > (this, R.layout.list_item, countries));
         lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                 public void onItemClick(AdapterView <? > arg0, View view, int position, long id) {
                     // When clicked, show a toast with the TextView text
                     Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
                         Toast.LENGTH_SHORT).show();

                 }

             });
     }
 }
Bellicose answered 7/3, 2012 at 6:21 Comment(6)
Items in the list are strings, is it possible to set those items clickable. I apologize if am missing anything here. I am a beginner in androidDetect
You shouldn't have to... Here is the Android tutorial if you haven't seen it. You can use setOnItemClickListener to get the behaviour you want, I believe.Bellicose
You are correct, but this works when the display contains only listview. Try creating a linearlayout and add listview to this linear layout. Then onitem click listener wont workDetect
I created a linearlayout and put the listview inside of it. I had no issues using the onItemClickListener. I have added EDIT 2 above to show exactly what I have.Bellicose
Thanks for your response. I have added the code that i have been trying. I haven't tried to implement the gui in the xml way, but it does not work if i do it programmaticallyDetect
In the xml file, the height and width of the listview are set to occupy the full screen. Instead of using fill_parent, if we use wrap_content so as to accommodate other views, then onclicklistener wont work. I guess it has got something to do with focus. I will see if i can get a way to solve this problemDetect
C
2
ListView myList;
myList = (ListView)findViewById(list_vew_id_in_xml)
myList.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View  view, int position, long id) 
        {
      //Toast.makeText(BritishCouncilActivity.this, "" + position, 2).show();
         }
 });
Cantankerous answered 7/3, 2012 at 10:21 Comment(0)
P
1

Edited Answer

Apply This Sample Please This Works For You I have Tested This Code

//ListviewActivity.java

 package com.anl.lk;

 public class ListviewActivity extends ListActivity { 

     static final String[] COUNTRIES = new String[] {

         "Afghanistan", "Albania", "Algeria", "American Samoa",
             "Andorra", "Angola", "Anguilla", "Antarctica",
             "Antigua and Barbuda", "Argentina", "Armenia", "Aruba",
             "Australia", "Austria", "Azerbaijan", "Bahrain",
             "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize",
             "Benin", "Bermuda", "Bhutan", "Bolivia",
             "Bosnia and Herzegovina", "Botswana", "Bouvet Island",
             "Brazil", "British Indian Ocean Territory"
     };

     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setListAdapter(new ArrayAdapter < String > (this,
                 android.R.layout.simple_list_item_1, COUNTRIES));
         getListView().setTextFilterEnabled(true);
     }

     @Override
     protected void onListItemClick(ListView l, View v, int position, long id) {
         // TODO Auto-generated method stub
         super.onListItemClick(l, v, position, id);

         new AlertDialog.Builder(this)
             .setTitle("Hello")
             .setMessage("from " + getListView().getItemAtPosition(position))
             .setPositiveButton("OK",
             new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int which) {}
             })
             .show();

         Toast.makeText(ListviewActivity.this,
             "ListView: " + l.toString() + "\n" +
             "View: " + v.toString() + "\n" +
             "position: " + String.valueOf(position) + "\n" +
             "id: " + String.valueOf(id),
             Toast.LENGTH_LONG).show();
     }

 }

//FirstPage

package com.anl.lk;

public class FirstPage extends Activity {

    @override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent sam = new Intent(FirstPage.this, ListviewActivity.class);
                    startActivity(sam);

                }
            });
    }
}

//Manifest File

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.anl.lk"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:label="@string/app_name"
        android:name=".FirstPage" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".ListviewActivity"    android:theme="@android:style/Theme.Dialog"></activity>
</application>

Please Use This Code it have your Solution

Pyrotechnic answered 7/3, 2012 at 6:14 Comment(5)
i mean for showing A pop up for an Activity we should use android:theme="@android:style/Theme.Dialog" in the manifest for the corresponding Activity so that it will Load Any Activity means even listview on that popup windowPyrotechnic
OnListItemClick will be available to override only when we extend listactivity class. But i wanted to display the list inside a popup window.Detect
please use this Code Updated And tested(Working Code)Pyrotechnic
Yes, i was able to get the solution.Detect
Downvoted this. No explanation of the code. Very non-constructive.Lymn
M
1

Insert this property against any listview item

android:onClick="buttonClicked"

then in you code

public void buttonClicked(View view)
{
    //Do what you want to do..
}
Magdeburg answered 7/3, 2012 at 6:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.