Android中如何在后台播放音频时更换背景图片

3

我想在Android应用程序中,在音频文件正在后台运行时更改图像,但遇到了问题。以下是我的代码:

public class SongActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_song);
        final RelativeLayout rel = (RelativeLayout)findViewById(R.id.activity_song);
        MediaPlayer mp = MediaPlayer.create(SongActivity.this,R.raw.thesong);
        mp.start();
        rel.setBackgroundResource(R.drawable.bday);
        Runnable r = new Runnable() {
            @Override
            public void run() {
                synchronized (this){
                try {
                    wait(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                }
            }
        };
        Thread test = new Thread(r);
        test.start();
        rel.setBackgroundResource(R.drawable.bday2);
}
}

请告知我是否可以修改它或者需要彻底重构。提前感谢您的帮助。
2个回答

2

在您的 XML 中添加 ID。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/linear_layout">

    </LinearLayout>

在代码中,只需替换

final RelativeLayout rel = (RelativeLayout)findViewById(R.id.activity_song);

使用

      final RelativeLayout rel = (RelativeLayout)findViewById(R.id.linear_layout);
      Resources res = getResources();
      Drawable drawable = res.getDrawable(R.drawable.image);
      rel.setBackground(drawable);

1
"在我看到你的代码时,你写的方式是:"

"。"
setContentView(R.layout.activity_song);
        final RelativeLayout rel = (RelativeLayout)findViewById(R.id.activity_song);

这里的问题在于activity_song只是一个xml布局文件名,而不是一个RelativeLayout,因此请将(RelativeLayout)findViewById(R.id.activity_song);替换为您的RelativeLayout id,然后您将获得所需的结果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接