当音频文件在android中的后台运行时更改背景图像

时间:2017-01-13 04:40:10

标签: android image audio

当我在后台运行音频文件时,我试图在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 个答案:

答案 0 :(得分: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 :(得分:1)

当我看到你的代码时,你写得像:

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

这里的问题是activity_song这只是一个xml layout文件名而不是RelativeLayout所以请用你的(RelativeLayout)findViewById(R.id.activity_song); ID更改RelativeLayout。然后你会得到你渴望的结果。