How do I start an Intent from an OnClickListener How do I start an Intent from an OnClickListener android android

How do I start an Intent from an OnClickListener


Your OnItemClickListener should not extend Activity. Instead, you should arrange for the OnItemClickListener to have access to your ListActivity instance. Any view that is already part of the activity (like the ListView) has access to the ListActivity instance via getContext(). Then implement onClick like this:

@Overridepublic void onClick(View v) {    Intent intent = new Intent(context, ShowDefinition.class);    context.startActivity(intent);}


There are two ways to implement an onItemClickListener. You don't need to create a new class. Maybe you can try it the easy way for now :)

Have your ListActivity implement AdapterView.OnItemClickListener

public class MyActivity extends ListActivity implements AdapterView.OnItemClickListener

Then in your ListActivity's onCreate set your onClickListener like this :

        ListView lstvwContacts = getListView();        lstvwContacts.setOnItemClickListener(this);

And then you can react to the click like this :

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {    switch (parent.getId()) {        case android.R.id.list: {            Log.v(TAG, "onItemClick");            Intent intent = new Intent(this, ShowDefinition.class);            startActivity(intent);        }        }}

That should do it for clicks. If you need to know when an item is selected you can look into AdapterView.OnItemSelectedListener

-I_Artist


Your conception is wrong, your OnItemClickListener shouldn't extends Activity and you should n't build a new onClickListener each time.

public class MainActivity extends Activity {    OnItemClickListener = null;   MainActivity() {    //Build your OnItemClickListener with a valid context    OnItemClickListener = new OnItemClickListener(this);   }   public View getView(int position, View convertView, ViewGroup parent) {   ...   //Here user the OnItemClickListener   }}