Skip to content Skip to sidebar Skip to footer

Adding Onclick Listener To Gridview Items (to Launch Unique Intents Depending On Position)

I have a gridView and I'd like to launch a different intent depending on the position of the item clicked. I've instantiated the following onClick listener which includes the valu

Solution 1:

from the android documentation for GridView:

gridview.setOnItemClickListener(new OnItemClickListener() {
    publicvoidonItemClick(AdapterView<?> parent, View v, int position, long id) {
        Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
    }
});

edit: It looks like the addNewImageToScreen() is where you are adding the ImageCells, so assuming that you can generate the intent in that scope..

Intentintent=newIntent(this, Activity1.class); // or whatever you want to runImageCellnewView= ...
newView.setTag( intent );

then in your onItemClick: public void onItemClick(AdapterView parent, View v, int position, long id) { Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show(); Intent intent = (Intent) v.getTag(); // now you can startActivity with your intent.. }

Solution 2:

Make a string array with your classes, the in the onItemClick () create another string declared with the position (item) clicked.

publicclassMainActivityextendsActivity {

    String [] classes = {"act1",  "act2"}; // activity files

    GridView gridView;

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    gridView = (GridView) findViewById(R.id.gridView);
    gridView.setAdapter(newImageAdapter(this));
    gridView.setOnItemClickListener(newOnItemClickListener() {
            @SuppressWarnings("rawtypes")publicvoidonItemClick(AdapterView<?> parent, View v, int position, long id) {

            Stringpos= classes[position];

            try {
            Classstart= Class.forName("com.company.app." + pos); //Your package nameIntenti=newIntent(MainActivity.this, start);
            startActivity(i);
            } catch(ClassNotFoundException e){
            e.printStackTrace();
            }

            Toast.makeText(
                getApplicationContext(),
                ((TextView) v.findViewById(R.id.label))
                .getText(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Post a Comment for "Adding Onclick Listener To Gridview Items (to Launch Unique Intents Depending On Position)"