2017-08-03 55 views
0

如何初始化的GridLayout孩子,在多個ImageView元素存在於GridLayout去另一個活動如何初始化子視圖的網格佈局

這裏設置onClickListener是我的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

這個問題有一些很好的修改的回滾,這是被認爲是類似於堆棧溢出破壞行爲我的XML佈局文件。如果有人在代碼元素上添加了代碼格式改進或其他更改,請留下它們。 – halfer

回答

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 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>