我正在尝试在其中创建一个带有ImageButtons的gridView,因此在按下时会发出声音。到目前为止,我有我的GridView_layout.xml,我的button.xml的布局。我的gridAdapter用按钮填充网格。使用我当前的代码,网格将填充按钮,但按下时不会发出声音。
这是我的按钮活动的一部分,它扩展了活动, 以下代码块在onCreate()方法中:
final Context context = getApplicationContext();
final int duration = Toast.LENGTH_SHORT;
final ImageButton one = (ImageButton) findViewById(R.id.imageButton);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.pears);
if (mp.isPlaying()) {
mp.stop();
mp.reset();
}
if (mp == null) {
Toast toast = Toast.makeText(context, "button error", duration);
toast.show();
} else {
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaplayer) {
mp.stop();
mp.release();
}
});
mp.start();
}
}
});
}
});
来自gridAdapter的getView()方法按要求:
public View getView(int position, View convertView, ViewGroup parent) {
ImageButton imageButton;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageButton = new ImageButton(mContext);
imageButton.setLayoutParams(new GridView.LayoutParams(190, 190));
imageButton.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageButton.setBackgroundColor(white);
} else {
imageButton = (ImageButton) convertView;
}
imageButton.setImageResource(mThumbIds[position]);
return imageButton;
}
答案 0 :(得分:0)
如果您想在按gridview中的项目时播放声音,请将代码更改为:
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.pears);
mPlayer .start();
}
});
如果您想在点击其中一个网格项内的按钮时播放声音,请在适配器的getview方法中使用此代码:
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.pears);
mPlayer .start();
}
});