简体   繁体   中英

How to Initialize child views for GridLayout

How to initialize child of GridLayout and set onClickListener on the multiple ImageView elements present in GridLayout to go on another activity

Here is my java code:

public class ResidentialActivity extends Activity {
    GridView grid;
    ImageView img1;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_residential);
        GridLayout grid= (GridLayout) findViewById(R.id.grid);
    }
}

This works for me. I am adding cells to a GridLayout and hooking up OnClick listeners to each.

If you already have populated your GridLayout, you could could use GridLayout.getChildCount() and GridLayout.getChildAt(i) to manipulate each cell to add an OnClick listener.

You need to first have your ResidentialActivity implement View.OnClickListener, like this:

public class ResidentialActivity extends AppCompatActivity implements View.OnClickListener {

and override the OnClick() method like:

@Override
protected void onClick(final View view) {
. . .  launch your other activity in here
}

To hook up the onClick you can iterate through the cells (you could use 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);
    }

where this is my xml layout file for 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM