TJ Riceball
TJ Riceball

Reputation: 238

My ListView wouldn't work. I'm missing out something here

I casted this line: lv1.setOnItemClickListener((OnItemClickListener) this); because it creates a red squiggly line. Am I using the onItemClick function properly?

 public class MainActivity extends Activity {

private ListView lv1;
private String lv_arr[] = {
        "Android",
        "iPhone",
        "Blackberry",
        "AndroidPeople"
};


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv1 = (ListView) findViewById(R.id.ListView01);
    lv1.setOnItemClickListener((OnItemClickListener) this);
    //by using setAdapter method in ListView, we can add string array in list

    lv1.setAdapter(new ArrayAdapter<String>(
            this, android.R.layout.simple_list_item_1, lv_arr));

}

public void onItemClick(AdapterView arg0, View v, int position, long arg3){

    Toast.makeText(this, "You clicked" + lv_arr[position],       Toast.LENGTH_LONG).show();

}



 }

Upvotes: 0

Views: 64

Answers (3)

nKn
nKn

Reputation: 13761

If you're trying to have each row with its customized onClickListener(), you'll need to extend an ArrayAdapter (for instance) and implement the onClickListener() for each row within the getView() method.

@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
  // Speaking very vaguely, convertView represents each of your rows
  if (convertView == null) {
    ...
    convertView.setOnClickListener(new View.OnClickListener() {
      public void onClick(final View v) {
        // Whetever you need
        ...
      }
    }
  });
  else
    ...

  // Rest of your implementation
  ...

  return convertView; 
}

Upvotes: 0

Matej Špil&#225;r
Matej Špil&#225;r

Reputation: 2687

you need to implement OnItemClickListener or just if you can write instead

 lv1.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            Toast.makeText(this, "You clicked" + lv_arr[position],       Toast.LENGTH_LONG).show();
        }
    });

Upvotes: 0

panini
panini

Reputation: 2026

Your MainActivity doesn't implement OnItemClickListener, which is why it was giving you the "red squigly line".

You should change the class declaration to:

public class MainActivity extends Activity implements OnItemClickListener {

this will mean that you don't have to cast your MainActivity to an OnItemClickListener when setting it to your ListView

Upvotes: 1

Related Questions