如何初始化GridLayout
的子项并在onClickListener
中的多个ImageView
元素上设置GridLayout
以继续进行其他活动
这是我的java代码:
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);
}
}
答案 0 :(得分:0)
这对我有用。我正在向GridLayout添加单元格并将OnClick侦听器连接到每个单元格。
如果您已经填充了GridLayout,则可以使用GridLayout.getChildCount()
和GridLayout.getChildAt(i)
来操作每个单元格以添加OnClick侦听器。
您需要首先让您的ResidentialActivity实现View.OnClickListener,如下所示:
public class ResidentialActivity extends AppCompatActivity implements View.OnClickListener {
并覆盖OnClick()方法,如:
@Override
protected void onClick(final View view) {
. . . launch your other activity in here
}
要连接onClick,您可以遍历单元格(可以使用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);
}
这是我的picture_cell
的xml布局文件<?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>