0

I used those code to make 2x2 Image on a GridLayout and it works, but there is one problem, each ImageView has the same ID, -1, so when I use OnClick it does not work. What can I do?

Here the codes

activity_main.xml :

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"      
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/gridLayout"
    tools:context=".MainActivity"
    android:orientation="horizontal" 
    android:columnCount="2"
    android:rowCount="2" />

MainActivity.java :

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GridLayout gridLayout = (GridLayout) findViewById(R.id.gridView);

        ImageView[][] imageViews = new ImageView[2][2];

        for (int i=0;i<2;i++){
            for (int j=0;j<2;j++){
                imageViews[i][j] = new ImageView(MainActivity.this);
                imageViews[i][j].setImageResource(R.mipmap.ic_launcher);
                gridLayout.addView(imageViews[i][j]);
            }
        }  
  }
}
ρяσѕρєя K
  • 127,886
  • 50
  • 184
  • 206

1 Answers1

0

Your view IDs only need to be positive integers, so could set them like this:

imageViews[i][j].setId(100);   // or whatever you prefer

OR you could set a click listener programmaticaly:

// Create the click listener
View.OnClickListener clickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // do what you want
    }
};

for (int i=0;i<2;i++){
    for (int j=0;j<2;j++){
        imageViews[i][j] = new ImageView(MainActivity.this);
        imageViews[i][j].setImageResource(R.mipmap.ic_launcher);
        imageViews[i][j].setOnClickListener(clickListener);
        gridLayout.addView(imageViews[i][j]);
    }
}
megaturbo
  • 658
  • 6
  • 23