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]);
}
}
}
}