【问题标题】:Android - Button changes backgroundimage for new activityAndroid - 按钮更改新活动的背景图像
【发布时间】:2018-03-18 01:33:31
【问题描述】:

我希望我的 Button 使用意图打开一个新活动。 这个我已经实现了,它可以工作。

我的问题是为这个新活动设置背景图片。

例如:

  • 当 button1 被按下时,新 Activity 打开时 image1 为 背景。
  • 当 button2 被按下时,新 Activity 打开时 image2 为 背景。

如果有人知道实现此功能的 Java 代码或我能在哪里找到它,那就太好了。

【问题讨论】:

  • 每次单击按钮时传递唯一值,以了解按下了哪个按钮。
  • 将捆绑包值从您的活动传递到第二个活动。在第二个活动中获取该捆绑包并根据它做出决定。

标签: java android image button background


【解决方案1】:

你可以做这样的事情。在两个按钮单击时调用以下函数并传递 button1 = 1 和 button2 = 2 的值。

/*
 *  Button 1 press then pass = 1
 *  Button 2 press then pass = 2
 * */
private void buttonPressed(int value)
{
    Intent intent = new Intent(YourActivity.this, SecondActivity.class);
    intent.putExtra("BUTTON_PRESSED", value);
    startActivity(intent);
}

现在在您的第二个活动中,只需从 Intent 获取值。

int whichButtonPressed = getIntent().getIntExtra("BUTTON_PRESSED", 0);

if (whichButtonPressed == 1)
{
    // Show image 1
}
else if (whichButtonPressed == 2)
{
    // Show Image 2
}

【讨论】:

    【解决方案2】:

    使用 Intent 向您的下一个活动发送价值

    intent.putExtra("button","button1");
    

    点击按钮。然后使用

    获取另一个活动的值
    String msg  = intent.getStringExtra("button");
    

    然后,通过检查值来执行操作。

    示例

    在按钮 1 上单击

    Intent intent = new Intent(MainActivity.this, SecondActivity.class);
    intent.putExtra("button","button1");
    startActivity(intent);
    

    在按钮 2 上单击

    Intent intent = new Intent(MainActivity.this, SecondActivity.class);
    intent.putExtra("button","button2");
    startActivity(intent);
    

    然后,在您的 SecondActivity onCreate() 方法中

    String msg  = intent.getStringExtra("button");
    
    if (msg.equals("button1"))
    {
        //yourlayout.setImageBacground(image1);
    }
    else 
    {
        //yourlayout.setImageBacground(image2);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多