androidNewbie androidNewbie - 4 months ago 32
Android Question

Android Studio Error: "Cannot find variable itemclicklistener", despite having already imported OnItemClickListener API

Why does Android Studio not recognize that I already imported the onClickListener API?

Error in the following line:
listView.setOnItemClickListener(itemClickListener);

Code for my main activity is below:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemClickListener;


public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView,
View v,
int position,
long id) {
if (position == 0) {
//main activity launches food categories when the food option is clicked
Intent intent = new Intent(MainActivity.this,
FoodCategories.class);
startActivity(intent);
}
}
};

//Add the listener to my listview
ListView listView = (ListView) findViewById(R.id.list_options);
listView.setOnItemClickListener(itemClickListener);

}
}

Answer
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> listView,
                                    View v,
                                    int position,
                                    long id) {
                if (position == 0) {
                    //main activity launches food categories when the food option is clicked
                    Intent intent = new Intent(MainActivity.this,
                            FoodCategories.class);
                    startActivity(intent);
                }
            }
        };

You have to create a variable before using it

Comments