【问题标题】:Changing background image on button click android app development更改按钮上的背景图像单击android应用程序开发
【发布时间】:2015-06-26 11:15:40
【问题描述】:

我正在尝试更改活动的背景图片 单击按钮,但无法这样做。你们能告诉我我该怎么做吗?

Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        try
        {
            Activity activity = Selection.this;
            //Drawable db = Drawable..createFromPath(R.drawable.love1);

            // The below line gives error because setbackgroundImage 
            // is supposed to take a drawable object as an argument. 
            // Now what to do?                                  
            activity.findViewById(android.R.id.content)
            .setBackground(Drawable.createFromPath("res/love1.jpg"));

            // What to do to correct the above line?

            mySong = MediaPlayer.create(Selection.this, R.raw.song1);
            mySong.start();
        }
        catch(Exception ee){
            TextView tv = (TextView) findViewById(R.id.textView1);
            tv.setText(ee.getMessage());
        }
    }
});

我尝试使用 setBackgroundColor 使用 Color.RED,但这也不起作用。 PS:我没有更改 xml 文件中的任何内容来完成此操作。

【问题讨论】:

  • 请提供.setBackground 中抛出的错误,并查看Drawable.createFromPath() 返回的内容(它确实是可绘制对象吗?createFromPath 成功了吗?)
  • 实际上没有抛出任何错误,唯一的问题是当我尝试使用 Drawable.createFrompath() 时,它说我所需的最低 API 级别是 16,而您使用的低于该级别。但是颜色的东西现在正在起作用。只有我无法更改背景。这次我遇到的问题是: 1. 我在 xml 的 Layout 标记中添加了一个 id,然后使用该 id 来更改颜色。 2.但我不能对背景(Drwawable)做同样的事情,因为它需要一个我无法提供的可绘制参数,并且请不要使用你上面的方法它不工作!!
  • 使用getResources().getDrawable(R.drawable.your_drawable)并将你的drawable(jpg)放在res/drawable文件夹中。您不能在 API 级别低于 16 的情况下使用 setBackground,您应该为此使用 setBackgroundDrawableSource and example on API level-dependent execution

标签: android android-intent android-fragments android-activity


【解决方案1】:

我认为最简单的方法是在您的活动中使用 xml 文件中的布局。例如:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/linearLayoutID" 
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="@drawable/background_img1" >

然后在您需要时从您的活动中更改它,例如按钮点击后:

 LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linearLayoutID);
 mLinearLayout.setBackgroundResource(R.drawable.background_img2);

【讨论】:

  • 谢谢 M_Y。它有效,但是当我看到您的解决方案时,我想为什么我还没有使用这种方法。我没有使用你的这两行,而是将我的 setBackground(Drawable) 更改为:activity.findViewById(android.R.id.content).setBackgroundResource(R.id.love1);
  • 很高兴它成功了!是的,这是另一种方式。
【解决方案2】:

setBackground(Drawable) 更改为 setBackgroundResource(R.drawable.filename)

【讨论】:

    【解决方案3】:

    LinearLayout mLLinearLayout = (LinearLayout) findViewById(R.id.LayoutID); mLLinearLayout.setBackgroundResource(R.drawable.image_name);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-14
      • 2017-03-07
      • 2013-04-25
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多