- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我是 Android 开发新手,目前我正在 Android 中实现简单的音乐播放器应用程序。所以,我的问题是我在此音乐播放器中使用 fragment ,并且我想在另一个 ListView fragment 中添加最近播放的歌曲。
这是我的主要播放器 fragment 类......
private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnPlaylist;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
private MediaPlayer mp;
VisualizerView mVisualizerView;
SliderView sl;
private Visualizer mVisualizer;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
private ArrayList<SongModel> songsList = new ArrayList<SongModel>();
int songIndex;
private AudioManager audioManager = null;
SongAdapter songAdapter;
public Player(int position) {
songIndex = position;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.player, container, false);
super.onCreate(savedInstanceState);
// variable initialization for button
btnPlay = (ImageButton) android.findViewById(R.id.btnPlay);
btnForward = (ImageButton) android.findViewById(R.id.btnForward);
btnBackward = (ImageButton) android.findViewById(R.id.btnBackward);
btnNext = (ImageButton) android.findViewById(R.id.btnNext);
btnPrevious = (ImageButton) android.findViewById(R.id.btnPrevious);
btnRepeat = (ImageButton) android.findViewById(R.id.btnRepeat);
btnShuffle = (ImageButton) android.findViewById(R.id.btnShuffle);
songProgressBar = (SeekBar) android.findViewById(R.id.songProgressBar);
songTitleLabel = (TextView) android.findViewById(R.id.songTitle);
songTitleLabel.setEllipsize(TextUtils.TruncateAt.MARQUEE);
songTitleLabel.setSingleLine(true);
songCurrentDurationLabel = (TextView)android.findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = (TextView) android.findViewById(R.id.songTotalDurationLabel);
mVisualizerView = (VisualizerView) android.findViewById(R.id.myvisualizerview);
audioManager = (AudioManager)getActivity().getSystemService(Context.AUDIO_SERVICE);
//get bundle data
/*Bundle b = getArguments();
int position = b.getInt("songIndex");
Log.i("position...","...."+position);*/
//Log.i("songIndex...","...."+);
//sliding finger up and increase and decrease volume
android.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
int action = MotionEventCompat.getActionMasked(event);
if (action == MotionEvent.ACTION_MOVE) {
// put your volume change logic here, for example compare previously recorded x/y position to new one and change volume
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 5, 0);
}
return true;
}
});
//Visualizer method
mp = new MediaPlayer();
initAudio();
// Mediaplayer
songManager = new SongsManager();
utils = new Utilities();
// Listeners
songProgressBar.setOnSeekBarChangeListener(this); // Important
mp.setOnCompletionListener(this); // Important
// Getting all songs list
songsList = songManager.getPlayList();
// By default play first song
if (songIndex==0)
{
playSong(0);
}
else
{
playSong(songIndex);
}
btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// check for already playing
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
btnPlay.setImageResource(R.drawable.btn_play);
}
} else {
// Resume song
if (mp != null) {
mp.start();
btnPlay.setImageResource(R.drawable.btn_pause);
}
}
}
});
btnForward.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
int currentPosition = mp.getCurrentPosition();
if(currentPosition + seekForwardTime <= mp.getDuration()){
mp.seekTo(currentPosition + seekForwardTime);
}else{
mp.seekTo(mp.getDuration());
}
}
});
btnBackward.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
int currentPosition = mp.getCurrentPosition();
if(currentPosition - seekBackwardTime >= 0){
mp.seekTo(currentPosition - seekBackwardTime);
}else{
mp.seekTo(0);
}
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(currentSongIndex < (songsList.size() - 1)){
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
}else{
playSong(0);
currentSongIndex = 0;
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(currentSongIndex > 0){
playSong(currentSongIndex - 1);
currentSongIndex = currentSongIndex - 1;
}else{
playSong(songsList.size() - 1);
currentSongIndex = songsList.size() - 1;
}
}
});
btnRepeat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(isRepeat){
isRepeat = false;
Toast.makeText(getActivity().getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
btnRepeat.setImageResource(R.drawable.btn_repeat);
}else{
isRepeat = true;
Toast.makeText(getActivity().getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
isShuffle = false;
btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}
}
});
btnShuffle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(isShuffle){
isShuffle = false;
Toast.makeText(getActivity().getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}else{
isShuffle= true;
Toast.makeText(getActivity().getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
isRepeat = false;
btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
btnRepeat.setImageResource(R.drawable.btn_repeat);
}
}
});
return android;
}
private void initAudio() {
getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
mp = MediaPlayer.create(getActivity(),R.raw.test);
mp.setLooping(true);
setupVisualizerFxAndUI();
mVisualizer.setEnabled(true);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mVisualizer.setEnabled(false);
}
});
mp.start();
}
private void setupVisualizerFxAndUI() {
mVisualizer = new Visualizer(mp.getAudioSessionId());
mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
mVisualizer.setDataCaptureListener(
new Visualizer.OnDataCaptureListener() {
public void onWaveFormDataCapture(Visualizer visualizer,
byte[] bytes, int samplingRate) {
mVisualizerView.updateVisualizer(bytes);
}
public void onFftDataCapture(Visualizer visualizer,
byte[] bytes, int samplingRate) {
}
}, Visualizer.getMaxCaptureRate() / 2, true, false);
}
@Override
public void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 100){
currentSongIndex = data.getExtras().getInt("songIndex");
// play selected song
playSong(currentSongIndex);
}
}
public void playSong(int songIndex){
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).getSongPath());
mp.prepare();
mp.start();
String songTitle = songsList.get(songIndex).getSongTitle();
songTitleLabel.setText(songTitle);
btnPlay.setImageResource(R.drawable.btn_pause);
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask,100);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
songProgressBar.setProgress(progress);
mHandler.postDelayed(this,100);
}
};
@Override
public void onCompletion(MediaPlayer mp) {
if(isRepeat){
playSong(currentSongIndex);
} else if(isShuffle){
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
} else{
if(currentSongIndex < (songsList.size() - 1)){
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
}else{
playSong(0);
currentSongIndex = 0;
}
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
mp.seekTo(currentPosition);
updateProgressBar();
}
@Override
public void onDestroy() {
super.onDestroy();
mHandler.removeCallbacks(mUpdateTimeTask);
if (mp != null) {
if (mp.isPlaying()) mp.stop();
mp.reset();
mp.release();
}
}
public void onBackPressed() {
new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.musiclogo)
.setTitle("Closing M-Player")
.setMessage("Are you sure you want to close this application?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
getActivity().finish();
}
})
.setNegativeButton("No",null)
.show();
}}
这是我的播放列表(歌曲列表) fragment 和扩展列表 fragment
EditText edtSearch;
ListAdapter adapter;
SongAdapter songAdapter;
ArrayList<SongModel> songList = new ArrayList<SongModel>();
SongsManager songsManager = new SongsManager();
// Songs list
public ArrayList<SongModel> songsList = new ArrayList<>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View windows = inflater.inflate(R.layout.playlist, container, false);
return windows;
}
@Override
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
edtSearch = (EditText)getView().findViewById(R.id.search);
final ArrayList<SongModel> songsListData = songsManager.songList;
Log.i("songsListData...",""+songsListData.size());
SongsManager plm = new SongsManager();
// get all songs from sdcard
this.songsList = plm.getPlayList();
// looping through playlist
for (int i = 0; i < songsListData.size(); i++) {
// creating new HashMap
SongModel song = songsListData.get(i);
// adding HashList to ArrayList
songsListData.add(song);
}
// Adding menuItems to ListView
/* adapter = new SimpleAdapter(getActivity(), songsListData, R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
R.id.songTitle });*/
songAdapter = new SongAdapter(getActivity(),songsList);
setListAdapter(songAdapter);
// selecting single ListView item
final ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View arg0,
int position, long id) {
// getting listitem index
Log.i("Index", "..." + position);
// Starting new intent
Intent i = new Intent(getActivity().getApplicationContext(),Main.class);
SongModel songModel = (SongModel) songAdapter.getItem(position);
int indexOfSong = songAdapter.songsList.indexOf(songModel);
// Sending songIndex to PlayerActivity
i.putExtra("songIndex", indexOfSong);
getActivity().setResult(100, i);
startActivityForResult(i, 100);
}
});
edtSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String text = edtSearch.getText().toString().toLowerCase(Locale.getDefault());
songAdapter.filter(text);
}
});
}
这是我的歌曲管理器类。
public ArrayList<SongModel> songList = new ArrayList<SongModel>();
// SDCard Path
final String MEDIA_PATH = new String("/sdcard/");
// Constructor
public SongsManager(){
}
public ArrayList<SongModel> getPlayList(){
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
SongModel setter = new SongModel();
setter.setSongPath(file.getPath());
setter.setSongTitle(file.getName().substring(0, (file.getName().length() - 4)));
songList.add(setter);
}
}
return songList;
}
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
这是我的歌曲适配器和扩展底座适配器。
Context context;
//private ArrayList<SongModel> songsList = null;
SongAdapter songAdapter;
private ArrayList<SongModel> songsListDat = null;
public ArrayList<SongModel> songsList;
private static LayoutInflater inflater;
public SongAdapter(FragmentActivity activity, ArrayList<SongModel> songsListDat) {
this.context = activity;
this.songsListDat = songsListDat;
this.songsList = new ArrayList<SongModel>();
this.songsList.addAll(songsListDat);
}
@Override
public int getViewTypeCount() {
return getCount();
}
@Override
public int getCount() {
return songsListDat.size();
}
@Override
public Object getItem(int position) {
return songsListDat.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.playlist_item, null);
TextView title = (TextView) vi.findViewById(R.id.songTitle); // title
SongModel song = new SongModel();
song = songsListDat.get(position);
// Setting all values in listview
title.setText(song.getSongTitle());
return vi;
如果有人知道这的逻辑,请帮助我。提前致谢
最佳答案
我终于做到了。这是我对此逻辑的更改
我创建了一个实用程序常量类并全局传递此数组列表。
public static ArrayList<SongModel> recentSongList = new ArrayList<SongModel>();
这是我的播放列表类,用于将单击的 ListView 项目发送到另一个 ListView
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View arg0,
int position, long id) {
Log.i("Index", "..." + position);
songAdapter.setSelectedIndex(position);
Intent i = new Intent(getActivity().getApplicationContext(),Main.class);
SongModel songModel = (SongModel) songAdapter.getItem(position);
int indexOfSong = songAdapter.songsList.indexOf(songModel);
// Sending songIndex to PlayerActivity
i.putExtra("songIndex", indexOfSong);
getActivity().setResult(100, i);
startActivityForResult(i, 100);
//putting song in recentSongList arraylist
SongModel model = (SongModel) songAdapter.getItem(position);
model.setSongTitle(songModel.getSongTitle());
model.setSongPath(songModel.getSongPath());
Constant.recentSongList.add(model);
Log.i("recentSongList...","..."+Constant.recentSongList.size());
}
});
这是我最近的播放列表 fragment ,用于在 ListView 中获取最近点击播放的歌曲
public class SingleItemView extends ListFragment{
SongAdapter songAdapter;
SongsManager songsManager = new SongsManager();
public ArrayList<SongModel> songsList = new ArrayList<>();
public ArrayList<SongModel> recentSongList = Constant.recentSongList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View windows = inflater.inflate(R.layout.recent_playlist, container, false);
Log.i("recent Song List...","..."+recentSongList.size());
return windows;
}
@Override
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
final ArrayList<SongModel> songsListData = songsManager.songList;
Log.i("songsListData...", "" + songsListData.size());
songAdapter = new SongAdapter(getActivity(),recentSongList);
setListAdapter(songAdapter);
final ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}}
关于java - 如何在 ListView 中添加最近播放的歌曲?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39303563/
我需要获取过去 24 小时的记录,但不能像这样按小时分组: SELECT HOUR(CompDate) AS hour, COUNT(1) AS action FROM mytable WHERE (
我们有一个自动完成列表,当您向某人发送电子邮件时会填充该列表,这一切都很好,直到列表变得非常大,您需要输入越来越多的地址才能找到您想要的地址, 这违背了自动完成的目的 我在想应该添加一些逻辑,以便自动
我在 android 的锁屏上工作我们如何禁用导航软按钮,已经尝试了所有方法,systemoverlay但它不起作用,在按下主页按钮时它会终止服务和 Activity 。 最佳答案 后退按钮可以通过覆
我有一个报告创建时间为 2016-05-30,现在我需要从报告时间开始的最后 7 天。我怎样才能使用时刻? report_create_time = moment('2016-05-30').form
我想找出向量中最接近的三个数字。 就像是 v = c(10,23,25,26,38,50) c = findClosest(v,3) c 23 25 26 我试过 sort(colSums(as.ma
考虑以下表结构: id speed 1 100 2 200 3 300 4 400 5 500 考虑以下查询:"SELECT * FROM records WHERE
我正在开发一个依赖 YouTube 直播和实时聊天(也来自 YouTube)的网络应用。事情进展顺利,突然嵌入的聊天功能无法在移动设备上运行。 我试图在我这边找到一个错误或一些无效的配置,但我找不到。
我正在制作一个 React Native 应用程序,它有一个安全部分,用户必须在其中输入密码才能解锁 protected 内容。问题是,当用户在锁定该部分之前切换到另一个应用程序时,将生成屏幕截图以及
我有一条 SQL 语句 (SQL Server Management Studio),我通过仪表板软件将数据传递到 where 语句中。用户可以选择年份(2013 年或现在的 2014 年)和月份(作
我有一个脚本可以添加一组行,使您能够在 SharePoint 列表表单中捕获其他访问者的信息。我有两个 anchor 标记,一个用于添加,另一个用于删除。当我添加一个新的访问者时它有效,当我删除访问者
我正在学习斯坦福 iOS 类(class),我有一个问题,我认为与最近的更新有关。这是代码部分: func evaluate(ops: [Op]) -> (result: Double?,remain
我注意到我的应用有一个奇怪的行为。每当我按下主页按钮时,我的应用程序就会被杀死。我没有在应用程序堆栈中看到该应用程序。我可以看到之前启动的其他应用程序。最初我怀疑 android:launchMode
我需要获取过去 7 天内的所有付费和临时条目,但我总是收到所有退回的内容。我不确定我做错了什么,我已经阅读了这里的很多帖子,但无法理解它是什么。 MySQL 5.6(如果它与我一直在做的事情有什么不同
我的表有一列以 mysql time() 格式格式化。 当它是一个值分配给名为 $preRemainOt 的 php 变量时我想重新安排到最近的 15 分钟 function roundTime($w
我想获取过去 7 天内每天每个产品的最后时间戳。数据库中有数千条记录。我怎样才能通过查询来做到这一点。大约有 25 种不同的产品,每种产品每天大约有 50 个时间戳。 表:构建数据 'Timesta
我现在的代码正在从 SQL 中获取移动应用程序中的数据,首先添加显示,我需要将其设置为在我的 Android 应用程序中显示最后添加的第一个。我有如下所示的 api 代码,最新的是根据我的要求显示的,
我有一张 table ,说 table 的描述为: | ID | SNO | c1 | c2 | c3 | ___________________________________ |
我有两个大小相等的向量,例如 A=[2.29 2.56 2.77 2.90 2.05] and B=[2.34 2.62 2.67 2.44 2.52]. 我有兴趣在两个相同大小的向量 A 和 B 中
之前,我在这里发布了一个问题,询问有关如何从驱动器读取和写入数据的建议,而不是通过像“aaa.txt”这样的文件标签,而只是扇区..我被建议尝试阅读和写作....但新问题出现了……毛茸茸的参数 int
我想删除在给定时间段内未登录的用户,但我稍后会根据结果选择时间段。 所以我需要报告,其中我将收到过去 1 个月、2 个月...... n 个月内未登录的用户数量。 我不太清楚如何在单个 mysql 查
我是一名优秀的程序员,十分优秀!