[英]How to add onClick method to ImageView inside a grid layout?
我正在創建一個類似井字游戲的游戲,其中包含一些圓形球,當用戶點擊他想要部署的房間時,這些圓形球會掉落。 我已將這些圖像添加到網格布局中,但是當用戶點擊它們時我無法運行專用方法。 我已將該方法分配給 imageview 的 onclick 屬性,但未執行 java 代碼。
編輯:當單擊網格布局並記錄時,我嘗試記錄一些內容。 所以結論是網格布局阻止了點擊注冊到imageview。
這是我的Java代碼:
public void dropIn(View view) {
ImageView counter = (ImageView) view;
counter.setTranslationY(1000f);
counter.setImageResource(R.drawable.yellow);
counter.animate().translationYBy(1000f).setDuration(300);
}
這是圖像視圖的 XML 代碼:
<ImageView
android:id="@+id/imageView5"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_margin="10dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="20dp"
android:onClick="dropIn"
app:layout_column="1"
app:layout_row="1" />
這是網格的 XML 代碼:
<android.support.v7.widget.GridLayout
android:layout_width="match_parent"
android:layout_height="360dp"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="185dp"
android:layout_marginEnd="6dp"
android:layout_marginRight="6dp"
android:layout_marginBottom="186dp"
android:background="@drawable/board"
app:columnCount="3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:rowCount="3">
您可以嘗試以編程方式執行此操作,而不是通過 XML 視圖分配方法。
首先,您需要創建一個新的 ImageView,然后使用 findViewById() 方法獲取呈現的視圖。 然后,使用“dropIn”邏輯分配 onClickListener:
ImageView counter = findViewById(R.id.imageView5);
counter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter.setTranslationY(1000f);
counter.setImageResource(R.drawable.yellow);
counter.animate().translationYBy(1000f).setDuration(300);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.