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

时间秒杀一切 提交于 2019-12-25 16:23:37

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/29021088/using-imagebuttons-to-switch-activities-how-can-i-switch-image-in-second-activi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!