[英]Using imageButtons to switch activities. How can I switch image in second activity based on button pressed?
我剛剛開始涉足Android開發。 現在,我在Android Studio中有一個程序,該程序具有兩列圖像,每列約6張圖像。 我要這樣做,所以如果我單擊該圖像,它將顯示在新活動中。 現在,我正在像這樣加載布局:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String name = intent.getStringExtra(Main.CHAMPION_NAME);
setContentView(R.layout.activity_champion_page);
}
setContentView中的布局如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="atree496.leaguestats.ChampionPage">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/azir"
android:id="@+id/imageView" />
</LinearLayout>
到目前為止,由於它是這樣設置的,因此它打開到一張圖像,但是我希望能夠使該圖像成為我單擊的圖像。 為此,我需要做哪些更改? 再次,我是新來的。 感謝您提供的任何幫助。
如果您將所按下圖像的int資源的文件名賦予xml中的Tag屬性,則可以向其添加意圖:
ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/azir"
android:tag="theImageFileName.png"
android:id="@+id/imageView" />
然后,您可以在按下它時對其進行檢索,並將其添加到您正在使用的Intent中:
@Override
public void onClick(View v) {
String fileName = (String) v.getTag();
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("fileName", fileName);
startActivity(intent);
}
在初始化secondImageView之后的第二個活動中:
String fileName = getIntent().getStringExtra("fileName");
int resId = getResources().getIdentifier(fileName,"drawable", getPackageName());
secondImage.setImageDrawable(getResources().getDrawable(resId));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.