1

I found this excellent tutorial on using icons for ListView items. http://www.debugrelease.com/2013/06/24/android-listview-tutorial-with-images-and-text/

I followed it exactly, and my ListView layout looks great! BUT...I can't get the onclick listener working for the ListView. I'm just stuck on the ListView screen. Here's my Main.java code where I put the listener. I'm using Deepak's (from above link) Item and ItemAdapter classes exactly with no changes. I only changed his Model class to put in my own icon file names. What am I missing?

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;

public class Main extends Activity {

ListView listView;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Model.LoadModel();
    listView = (ListView) findViewById(R.id.listView);
    String[] ids = new String[Model.Items.size()];
    for (int i= 0; i < ids.length; i++){

        ids[i] = Integer.toString(i+1);
    }

    ItemAdapter adapter = new ItemAdapter(this,R.layout.row, ids);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new OnItemClickListener(){

        @Override
        public void onListItemClick(ListView l, View v, int position, long id){

            Intent i;
            switch (position) {
            case 0:
                i = new Intent(this, AnglesConvert.class);
                startActivity(i);
                break; 
            case 1:
                i = new Intent(this, AreaConvert.class);
                startActivity(i);
                break;
        }
    });    

}

Thanks Ankur, I revised the Main.java file as above. Now I got red squiggles under Everything. Not sure what I'm doing wrong.

3 Answers 3

2

You need to call

listview.setOnClickListener(onListItemClick()) ;

After

listview.setAdapter(adapter) ;
Sign up to request clarification or add additional context in comments.

Comments

2

Use have not attached listener to it, Use this

listview.setOnItemClickListener(new onItemClickListener(){

@Override
protected void onListItemClick(){

//Do stuff
}
});    

2 Comments

Maybe this should work, but it doesn't. Please see my new Main.java file above. Now it has red squiggles under everything. Any idea what I did wrong?
Is there only two items (rows) in your list?
1

For onListItemClick to work. extend your class with ListActivity.

public class Main extends ListActivity {

Refer standard example

http://developer.android.com/guide/topics/ui/layout/listview.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.