adding onClick listener to gridView items (to launch unique intents depending on position)

前端 未结 2 1573
别跟我提以往
别跟我提以往 2021-01-16 21:13

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

相关标签:
2条回答
  • 2021-01-16 21:41

    from the android documentation for GridView:

    gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(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..

    Intent intent = new Intent(this, Activity1.class); // or whatever you want to run
    ImageCell newView = ...
    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.. }

    0 讨论(0)
  • 2021-01-16 22:00

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

    public class MainActivity extends Activity {
    
        String [] classes = {"act1",  "act2"}; // activity files
    
        GridView gridView;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        gridView = (GridView) findViewById(R.id.gridView);
        gridView.setAdapter(new ImageAdapter(this));
        gridView.setOnItemClickListener(new OnItemClickListener() {
                @SuppressWarnings("rawtypes")
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    
                String pos = classes[position];
    
                try {
                Class start = Class.forName("com.company.app." + pos); //Your package name
    
                Intent i = new Intent(MainActivity.this, start);
                startActivity(i);
                } catch(ClassNotFoundException e){
                e.printStackTrace();
                }
    
                Toast.makeText(
                    getApplicationContext(),
                    ((TextView) v.findViewById(R.id.label))
                    .getText(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题