问题在于声音无法播放。
当我运行应用程序时,这句话出现在(Android Mointor)“D / AbsListView:unregisterIRListener()被称为”
MainActivity.java代码
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
//instantiate custom adapter
List adapter = new List(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.listView);
lView.setAdapter(adapter);
}
}
List.java代码:
public class List extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
MediaPlayer mediaPlayer;
public List(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int pos) {
return list.get(pos);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.activity_list, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button addBtn = (Button)view.findViewById(R.id.add_btn);
addBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
MediaPlayer.create(List.this.context, R.raw.people)
mediaPlayer.start();
notifyDataSetChanged();
}
});
return view;
}
}
答案 0 :(得分:1)
试试这个:
@Override
public void onClick(View v) {
mediaPlayer = MediaPlayer.create(context,R.raw.people);
mediaPlayer.start();
notifyDataSetChanged();
}
答案 1 :(得分:1)
您可以使用以下方法播放声音。它可以通过互联网的存储或网址播放。
public void playAudio(String audioPath) {
try {
MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(audioPath);
mp.prepare();
mp.start();
Log.d(TAG, "is playing audio...");
} catch (Exception e) {
Log.d(TAG, "cannot play audio: " + e.toString());
}
}
答案 2 :(得分:1)
我认为您必须将this
更改为context
addBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
mediaPlayer.create(context,R.raw.people);
mediaPlayer.start();
notifyDataSetChanged();
}
});