繁体   English   中英

使用imageButtons切换活动。 如何在按下按钮的第二个活动中切换图像?

[英]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中的T​​ag属性,则可以向其添加意图:

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.

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