Cette travaille pour moi. J'ajoute des cellules à un GridLayout et j'accroche les écouteurs OnClick à chacun.
Si vous avez déjà rempli votre GridLayout, vous pouvez utiliser GridLayout.getChildCount()
et GridLayout.getChildAt(i)
pour manipuler chaque cellule afin d'ajouter un écouteur OnClick.
Vous devez d'abord votre ResidentialActivity mettre en œuvre View.OnClickListener, comme ceci:
public class ResidentialActivity extends AppCompatActivity implements View.OnClickListener {
et passer outre la méthode comme OnClick():
@Override
protected void onClick(final View view) {
. . . launch your other activity in here
}
Pour brancher le onClick vous pouvez itérer à travers les cellules (vous pouvez utiliser GridLayout.getChildCount()):
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout);
gridLayout = (GridLayout) findViewById(R.id.gl_puzzle);
. . .
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < NUM_CELLS; i++) {
RelativeLayout tmpCell = (RelativeLayout) inflater.inflate(R.layout.picture_cell, gridLayout, false);
ImageView pic = tmpCell.findViewById(R.id.iv_cell_image);
pic.setImageBitmap(pieces.get(i));
tmpCell.setOnClickListener(this);
gridLayout.addView(tmpCell);
}
où cela est mon fichier xml pour la mise en page picture_cell
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl_cell"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/iv_cell_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:background="@android:color/background_dark"
android:minHeight="20dp"
android:minWidth="20dp"
android:padding="1dp" />
</RelativeLayout>
Cette question a un certain nombre de rollbacks de bonnes modifications, ce qui est un comportement qui est considéré comme proche de vandalisme sur le débordement de pile. Si quelqu'un ajoute des améliorations de formatage de code à des éléments de code, ou d'autres bons changements, veuillez les laisser être. – halfer