我想在ListView
中添加一个按钮来播放声音。问题是IDE(在List.java中)无法解析此方法
mediaPlayer.create(this,R.raw.people);
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(this,R.raw.people);
mediaPlayer.start();
notifyDataSetChanged();
}
});
return view;
}
}
答案 0 :(得分:0)
方法签名为MediaPlayer create (Context context, int resid)
View.OnClickListener
不是Context
,在这种情况下this
就是BaseAdapter
。 Context
也不是MediaPlayer.create(List.this.context, R.raw.people)
。
您可以使用{{1}}
在适配器中声明它