簡體   English   中英

如何在類構造函數中正確使用 findViewById?

[英]How to properly use findViewById inside class constructor?

我正在嘗試將 id 應用於 ImageButton,但它在構造函數內的最后一行崩潰。

它在循環的第一次迭代時崩潰

這是我的 xml:

<LinearLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:layout_weight="1"
  android:gravity="center"
  android:orientation="vertical">

  <ImageView
    android:id="@+id/imageView0"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:adjustViewBounds="true"
    android:onClick="makeMove"
    android:tag="0"
    android:scaleType="centerInside"
    app:srcCompat="@drawable/white" />

  //imageView1 ... imageView41

  <ImageView
    android:id="@+id/imageView41"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:adjustViewBounds="true"
    android:scaleType="centerInside"
    app:srcCompat="@drawable/white" />

</LinearLayout>

圖像按鈕類:

我不得不在構造函數中使用 MainActity,因為我無法訪問 findViewById 方法。

public class ImageButtonClass 
{

    int id;
    int arrId;
    String color;
    ImageButton imageButton;

    ImageButtonClass(MainActivity mainActivity, int id, int arrId)
    {
    this.arrId = arrId;
    this.id = id;
    this.color = "White";

    //crashes on next line.
    imageButton = (ImageButton) mainActivity.findViewById(arrId); 
    }

}

和主要活動:

我使用 getResources 是因為 XML 中的所有 Id 都具有相同的名稱和不同的結尾。

ArrayList<ImageButtonClass> mBoard;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mBoard = new ArrayList<>();

    for(int i = 0; i < 42; i++)
    {
    int itemId = getResources().getIdentifier("imageView" + i, "id", 
    getPackageName());
    mBoard.add(new ImageButtonClass(this,i,itemId));
    }
}

java.lang.ClassCastException: android.support.v7.widget.AppCompatImageView 不能轉換為 android.widget.ImageButton

也許你會看到這個例外。

ImageView 不能轉換為 ImageButton。

將您的視圖類型 imageview 更改為 imagebutton 或更改 ImageButtonClass-imageButton 的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM