1 回答
TA貢獻1828條經(jīng)驗 獲得超6個贊
您需要重新定位 的初始化步驟,并將其放在方法MediaPlayer內(nèi)部onCreate
import android.support.v7.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.widget.ImageView;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity
{
? ? private MediaPlayer mediaPlayer;
? ? private ImageView playImageView;
? ? @Override
? ? protected void onCreate(Bundle savedInstanceState)
? ? {
? ? ? ? super.onCreate(savedInstanceState);
? ? ? ? setContentView(R.layout.activity_main);
? ? ? ? mediaPlayer = MediaPlayer.create(this, R.raw.anthem);
? ? ? ? playImageView = (ImageView) findViewById(R.id.playImageView);
? ? ? ? playImageView.setOnClickListener(new View.OnClickListener()
? ? ? ? {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onClick(View view)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? mediaPlayer.start();
? ? ? ? ? ? }
? ? ? ? });
? ? }
}
合適的布局文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
? ? ? ? ? ? ? xmlns:app="http://schemas.android.com/apk/res-auto"
? ? ? ? ? ? ? xmlns:tools="http://schemas.android.com/tools"
? ? ? ? ? ? ? android:layout_width="match_parent"
? ? ? ? ? ? ? android:layout_height="match_parent"
? ? ? ? ? ? ? android:orientation="vertical"
? ? ? ? ? ? ? android:layout_marginTop="0.5dp">
? ? <ImageView
? ? ? ? ? ? android:layout_gravity="center_horizontal"
? ? ? ? ? ? android:layout_width="wrap_content"
? ? ? ? ? ? android:layout_height="wrap_content"
? ? ? ? ? ? android:src="@android:drawable/ic_media_play"
? ? ? ? ? ? android:background="@android:color/black"
? ? ? ? ? ? android:clickable="true"
? ? ? ? ? ? android:focusable="true"
? ? ? ? ? ? android:id="@+id/playImageView"
? ? />
</LinearLayout>
添加回答
舉報
