列表视图上的搜索过滤器在点击时返回错误的结果

问题 我正在使用 android studio 创建音乐播放器。 一切都很好,直到我添加了搜索过滤器来搜索歌曲。 搜索过滤器正确返回歌曲,但当我点击搜索结果时,打开了错误的音乐文件,但播放器活动中显示的音乐名称是正确的,但播放的歌曲每次都是列表的第一首歌曲。 示例 有 4 首歌曲项目命名为:A、B、C、D 搜索 C 时,显示过滤结果 C。但是当点击它时,会显示歌曲名称 C,但会播放歌曲 A。

这真的很令人沮丧。

activity.java

package com.example.musicplayer2;

import android.Manifest;
import android.content.Intent;
import android.icu.text.Transliterator;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SearchEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatactivity;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;

import java.io.File;
import java.util.ArrayList;

public class Mainactivity extends AppCompatactivity {

    static boolean shuffleBol = false;
    static boolean loopBol = false;


    ListView listView;
    String[] items;
    ArrayAdapter<String> myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = findViewById(R.id.listViewSong);
        runtimePermission();

    }


    public void runtimePermission()
    {

        Dexter.withContext(this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                .withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
                        displaySongs();
                    }

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {

                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest,PermissionToken permissionToken) {

                        permissionToken.continuePermissionRequest();
                    }
                }).check();

    }


    public ArrayList<File> findSong(File file)
    {
        ArrayList<File> arrayList = new ArrayList<>();

        File[] files = file.listFiles();
        if (files != null){

            for (File singlefile : files)
            {
                if (singlefile.isDirectory() && !singlefile.isHidden())
                {
                    arrayList.addAll(findSong(singlefile));
                }

                else
                {
                    if (singlefile.getName().endsWith(".mp3") && !singlefile.getName().startsWith("."))
                    {
                        arrayList.add(singlefile);
                    }
                }
            }
        }

        return arrayList;
    }



    void displaySongs()
    {
        ArrayList<File> mysongs;
        mysongs = findSong(Environment.getExternalStorageDirectory());

        items = new String[mysongs.size()];

        for (int i=0; i < mysongs.size(); i++)
        {
            items[i] = mysongs.get(i).getName().replace(".mp3","");

        }

//        ArrayAdapter<String> myAdapter;
        myAdapter = new ArrayAdapter<String>(Mainactivity.this,android.R.layout.simple_list_item_1,items);
        listView.setadapter(myAdapter);


        listView.setOnItemClicklistener(new AdapterView.OnItemClicklistener() {
            @Override
            public void onItemClick(AdapterView<?> parent,View view,int position,long id) {
                String songName = (String) listView.getItemAtPosition(position);
                startactivity(new Intent(getapplicationContext(),Playeractivity.class)
                .putExtra("songs",mysongs)
                .putExtra("songname",songName)
                .putExtra("position",position));
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu,menu);

        MenuItem menuItem = menu.findItem(R.id.search_view);

        SearchView searchView = (SearchView) menuItem.getactionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                myAdapter.getFilter().filter(newText);
                return false;
            }
        });

        return super.onCreateOptionsMenu(menu);
    }



}

main activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".Mainactivity">


    <ListView
        android:id="@+id/listViewSong"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@android:color/transparent"
        android:dividerHeight="10.0sp"
        android:padding="8dp"
        >

    </ListView>

</RelativeLayout>

Playeractivity.java

package com.example.musicplayer2;

import androidx.appcompat.app.AppCompatactivity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.io.File;
import java.util.ArrayList;
import java.util.Random;

import static com.example.musicplayer2.Mainactivity.loopBol;
import static com.example.musicplayer2.Mainactivity.shuffleBol;

public class Playeractivity extends AppCompatactivity {

    ImageView btnplay,btnnext,btnprev,btnshuffle,btnloop;
    TextView txtsname,txtstart,txtstop;
    SeekBar seekmusic;

    String sname;

    public static final String EXTRA_NAME = "song_name";
    static MediaPlayer mediaPlayer;
    int position;
    ArrayList<File> mySongs;

    Thread updateseekbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);

        getSupportactionBar().setDisplayHomeAsUpEnabled(true);
        getSupportactionBar().setTitle("Player");


        btnprev = findViewById(R.id.btnprev);
        btnnext = findViewById(R.id.btnnext);
        btnplay = findViewById(R.id.playbtn);
        btnshuffle = findViewById(R.id.btnshuffle);
        btnloop = findViewById(R.id.btnloop);


        txtsname = findViewById(R.id.txtsn);
        txtstart = findViewById(R.id.txtstart);
        txtstop = findViewById(R.id.txtstop);

        seekmusic = findViewById(R.id.seekbar);




//        if a media player is already running then.
        if (mediaPlayer != null)
        {
            mediaPlayer.stop();
            mediaPlayer.release();
        }

        Intent i = getIntent();
        Bundle bundle = i.getExtras();

        mySongs = (ArrayList)bundle.getParcelableArrayList("songs");
        String songName = i.getStringExtra("songname");
        position = bundle.getInt("position",0);
        txtsname.setSelected(true);

        Uri uri = Uri.parse(mySongs.get(position).toString());
        sname = mySongs.get(position).getName();
        txtsname.setText(sname);

        mediaPlayer = MediaPlayer.create(getapplicationContext(),uri);
        mediaPlayer.start();

        updateseekbar = new Thread()
        {
            @Override
            public void run() {
                int totalDuration = mediaPlayer.getDuration();
                int currentPosition = 0;
                while (currentPosition<totalDuration)
                {
                    try {
                        sleep(500);
                        currentPosition = mediaPlayer.getcurrentPosition();
                        seekmusic.setProgress(currentPosition);
                    }

                    catch (InterruptedException | IllegalStateException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        };

        seekmusic.setMax(mediaPlayer.getDuration());
        updateseekbar.start();

        seekmusic.setOnSeekBarchangelistener(new SeekBar.OnSeekBarchangelistener() {
            @Override
            public void onProgressChanged(SeekBar seekBar,int progress,boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

                mediaPlayer.seekTo(seekBar.getProgress());
            }
        });

        String endTime = createTime(mediaPlayer.getDuration());
        txtstop.setText(endTime);

        final Handler handler = new Handler();
        final int delay = 1000;
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String currentTime = createTime(mediaPlayer.getcurrentPosition());
                txtstart.setText(currentTime);
                handler.postDelayed(this,delay);
            }
        },delay);

        //        click Listener ON PLAY button

        btnplay.setOnClicklistener(new View.OnClicklistener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer.isPlaying())
                {
                    btnplay.setBackgroundResource(R.drawable.play);
                    mediaPlayer.pause();
                }

                else
                {
                    btnplay.setBackgroundResource(R.drawable.pause);
                    mediaPlayer.start();
                }
            }
        });

        //        click Listener ON next button

        btnnext.setOnClicklistener(new View.OnClicklistener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.stop();
                mediaPlayer.release();

                if (shuffleBol && !loopBol){
                    position=getRandom((mySongs.size()));
                }

                else if(!shuffleBol && !loopBol)
                {
                    position=((position+1)%mySongs.size());
                }

                Uri u = Uri.parse(mySongs.get(position).toString());
                mediaPlayer = MediaPlayer.create(getapplicationContext(),u);
                sname=mySongs.get(position).getName();
                txtsname.setText(sname);
                mediaPlayer.start();
                btnplay.setBackgroundResource(R.drawable.pause);
                String endTime = createTime(mediaPlayer.getDuration());
                txtstop.setText(endTime);

            }
        });


        //        click Listener ON previous button

        btnprev.setOnClicklistener(new View.OnClicklistener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.stop();
                mediaPlayer.release();



                if (shuffleBol && !loopBol){
                    position=getRandom((mySongs.size()));
                }

                else if(!shuffleBol && !loopBol){
                        position=((position-1)<0)?(mySongs.size()-1):(position-1);
                }

                Uri u = Uri.parse(mySongs.get(position).toString());
                mediaPlayer = MediaPlayer.create(getapplicationContext(),u);
                sname=mySongs.get(position).getName();
                txtsname.setText(sname);
                mediaPlayer.start();
                btnplay.setBackgroundResource(R.drawable.pause);
                String endTime = createTime(mediaPlayer.getDuration());
                txtstop.setText(endTime);
            }
        });

        //        click listener for shuffle btn

        btnshuffle.setOnClicklistener(new View.OnClicklistener() {
            @Override
            public void onClick(View v) {
                if (shuffleBol){
                    shuffleBol=false;
                    btnshuffle.setImageResource(R.drawable.shuffle_off);
                }

                else {
                    shuffleBol=true;
                    btnshuffle.setImageResource(R.drawable.shuffle_on);
                }

            }
        });

        //        click listener for loop btn

        btnloop.setOnClicklistener(new View.OnClicklistener() {
            @Override
            public void onClick(View v) {
                if (loopBol){
                    loopBol=false;
                    btnloop.setImageResource(R.drawable.loop_off);
                }

                else {
                    loopBol=true;
                    btnloop.setImageResource(R.drawable.loop_on);
                }
            }
        });



//        next Listener ON song completion

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                btnnext.performClick();
            }
        });






    }


    public String createTime(int duration)
    {
        String time = "";
        int min = duration/1000/60;
        int sec = duration/1000%60;

        time+=min+":";

        if (sec<10)
        {
            time+="0";
        }
        time+=sec;

        return time;
    }

    private int getRandom(int i) {
        Random random= new Random();
        return random.nextInt(i+1);
    }

}

Playeractivity.xml

<?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="wrap_content"
    android:background="@drawable/bg"
    android:orientation="vertical"
    android:weightSum="10"
    tools:context=".Playeractivity"
    android:baselineAligned="false">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="7"
        android:gravity="center"
        android:orientation="vertical"
        tools:ignore="Suspicious0dp,Uselessparent">

        <TextView
            android:id="@+id/txtsn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="0dp"
            android:ellipsize="marquee"
            android:marqueeRepeatLimit="marquee_forever"

            android:singleLine="true"
            android:text="@string/song_name"
            android:textAlignment="center"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="italic">

        </TextView>

        <ImageView
            android:id="@+id/imageview"
            android:layout_width="250dp"
            android:layout_height="250dp"
            android:layout_marginBottom="8dp"
            android:src="@drawable/logo">

        </ImageView>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="60dp">

            <SeekBar
                android:id="@+id/seekbar"
                android:layout_width="250dp"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerInParent="true"
                android:layout_margin="20dp"
                android:layout_marginBottom="40dp">

            </SeekBar>

            <TextView
                android:id="@+id/txtstart"
                android:layout_width="78dp"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="false"
                android:layout_centerInParent="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="-17dp"
                android:layout_toLeftOf="@+id/seekbar"
                android:text="0:00"
                android:textAlignment="center"
                android:textColor="@color/black"
                android:textSize="15sp">

            </TextView>

            <TextView
                android:id="@+id/txtstop"
                android:layout_width="78dp"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="false"
                android:layout_centerInParent="true"
                android:layout_marginLeft="-14dp"
                android:layout_marginRight="20dp"
                android:layout_toRightOf="@+id/seekbar"
                android:text="@string/_4_10"
                android:textAlignment="center"
                android:textColor="@color/black"
                android:textSize="15sp">

            </TextView>

        </RelativeLayout>


    </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="98dp"
        android:layout_weight="3">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/playbtn"
                android:layout_width="70dp"
                android:layout_height="70dp"
                android:layout_centerHorizontal="true"
                android:background="@drawable/pause" />

            <ImageView
                android:id="@+id/btnnext"
                android:layout_width="55dp"
                android:layout_height="55dp"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:layout_toRightOf="@+id/playbtn"
                android:background="@drawable/next" />

            <ImageView
                android:id="@+id/btnprev"
                android:layout_width="55dp"
                android:layout_height="55dp"
                android:layout_marginTop="10dp"
                android:layout_marginRight="20dp"
                android:layout_toLeftOf="@+id/playbtn"
                android:background="@drawable/previous" />

            <ImageView
                android:id="@+id/btnshuffle"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_toLeftOf="@+id/btnprev"
                android:layout_marginTop="85dp"
                android:layout_marginRight="35dp"
                android:background="@drawable/shuffle_off"/>

            <ImageView
                android:id="@+id/btnloop"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_toRightOf="@+id/btnnext"
                android:layout_marginTop="85dp"
                android:layout_marginLeft="35dp"
                android:background="@drawable/loop_off"/>





        </RelativeLayout>

    </LinearLayout>

</LinearLayout>
jhyk6922 回答:列表视图上的搜索过滤器在点击时返回错误的结果

enter image description here

在上图中,您看到您正在发送过滤数组的位置并发送未过滤的歌曲列表(mysongs)。这就是它发生的原因。

所以你需要做的是要么发送过滤后的数组。或者添加一些逻辑来从歌曲列表中获取正确的位置。就是这样。

如果你不明白,请告诉我我会更新适当的逻辑。

本文链接:https://www.f2er.com/4386.html

大家都在问