問題描述
我如何使用數組來顯示匹配的 Imageview? (How Could I use array to show match Imageview?)
我得到一些像這樣的數據:{201,501,301,404,211}
我使用 ',' 來分割
String[] messages = split(",");
所以我得到 201 501 301 404 211 ,現在我只需要三個值:201 501 301
messages[0]; //201
messages[1]; //501
messages[2]; //301
但是,我有九個圖標,根據消息[0] ~ 消息[2]
只有三個圖標會顯示:
/p>
<ImageView
android:id="@+id/ig_p1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="@dimen/precaution_top"
android:src="@mipmap/icon_101" />
<ImageView
android:id="@+id/ig_p2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/precaution_top"
android:layout_toRightOf="@+id/ig_precaution_1"
android:src="@mipmap/icon_403" />
<ImageView
android:id="@+id/ig_p3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/precaution_top"
android:layout_toRightOf="@+id/ig_precaution_2"
android:src="@mipmap/icon_401" />
根據我的xml,只有三個ImageView會顯示,我想顯示array[0] ~ array[2]來匹配imageView。
ImageView p1,p2,p3;
p1 = (ImageView)findViewById(R.id.ig_p1);
p2 = (ImageView)findViewById(R.id.ig_p2);
p3 = (ImageView)findViewById(R.id.ig_p3);
請幫助我,謝謝.
參考解法
方法 1:
You can set icons dynamically.
Create a function and call 3 times.
ig_p1ImageView, ig_p2ImageView, and ig_p3ImageView are image views that you use in Java side with findViewById().
void setIcon(String iconName, ImageView imageView ) {
String fileName = "icon_" + iconName
int iconResId = getResources().getIdentifier(fileName, "mipmap", getPackageName());
imageView.setImageResource(iconResId);
}
setIcon(messages[0], ig_p1ImageView );
setIcon(messages[1], ig_p2ImageView );
setIcon(messages[2], ig_p3ImageView );