简体   繁体   中英

Using imageButtons to switch activities. How can I switch image in second activity based on button pressed?

I am just starting to dabble with Android development. Right now, I have a program in Android Studio that has two columns of images about 6 images each. I want to make it so if I click that image, it will appear in the new activity. Right now, I am just loading the layout like this:

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    String name = intent.getStringExtra(Main.CHAMPION_NAME);
    setContentView(R.layout.activity_champion_page);

}

With the layout in setContentView looking like this:

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

As of now, it opens to the one image because that is how it is set up, but I want to be able to have the image be the one that I click. What changes do I need to do in order to achieve this? Again, I am new to this. Thank you for any help you can give.

You could add to the intent the int resource of your pressed image if you give it file name to Tag attribute in xml:

ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/azir"
android:tag="theImageFileName.png"
android:id="@+id/imageView" />

Then you could retreive it when pressed and add it to the Intent you are using:

 @Override
 public void onClick(View v) {
     String fileName = (String) v.getTag();
     Intent intent = new Intent(this, SecondActivity.class);
     intent.putExtra("fileName", fileName);
      startActivity(intent);
 }

In second activity after you initialize the secondImageView:

String fileName = getIntent().getStringExtra("fileName");
int resId = getResources().getIdentifier(fileName,"drawable", getPackageName());
secondImage.setImageDrawable(getResources().getDrawable(resId));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM