ListView 项目在滚动后保持突出显示

Posted

技术标签:

【中文标题】ListView 项目在滚动后保持突出显示【英文标题】:ListView item stays highlighted once scrolled 【发布时间】:2016-01-09 22:55:55 【问题描述】:

我的应用程序中有一个列表视图,如果我单击列表中的一项,它会突出显示。然后,如果我单击另一个项目,则突出显示将转移到该项目。但是,如果在选择一个项目后滚动列表,然后从列表的另一部分选择另一个项目,它们都会保持突出显示。但如果我不滚动屏幕就不会。这是什么原因造成的?又该如何处理?

ListAdapter.java

package com.example.mp3;



import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListAdapter extends BaseAdapter

    private Context _context;
    private List<String> list;

    public  ListAdapter(Context _context,List<String> list)
    
        this._context=_context;
        this.list=list;
    
    @Override
    public int getCount() 
        // TODO Auto-generated method stub
        return list.size();
    

    @Override
    public Object getItem(int arg0) 
        // TODO Auto-generated method stub
        return list.get(arg0);
    

    @Override
    public long getItemId(int arg0) 
        // TODO Auto-generated method stub
        return arg0;
    
     @Override

        public int getViewTypeCount() 

         return getCount();
        

        @Override

        public int getItemViewType(int position) 

         return position;
        


    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) 
        // TODO Auto-generated method stub

           View row = convertView;
            if (convertView == null) 
                LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(R.layout.simplerow, viewGroup, false);
            


            TextView textView = (TextView) row.findViewById(R.id.rowTextView);
            textView.setText(list.get(position).toString());



        return row;
    




MainActivity.java

package com.example.mp3;


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

import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;

import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.MenuItemCompat.OnActionExpandListener;
import android.text.html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;


public class MainActivity extends Activity implements View.OnClickListener, OnCompletionListener 

    ListView list;
    ArrayAdapter<String> adapter ;
    ArrayList<String> listTest;
     ArrayList<String> listSoundNames;
    ImageButton play,stop,back,next;
    String songpath,song,title;
    int index,current_position;
    File[] listFile;
    SharedPreferences sharedPref;
    MediaPlayer mp,mp2;
    ActionBar bar;
    private Boolean state=false;
    private static int save = -1;
    int count=0;
    private static final String TAG = MainActivity.class.getSimpleName();
    private Context _context = this;


    @Override
    protected void onCreate(Bundle savedInstanceState) 



        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        song = sharedPref.getString("songname", "name");

        mp=new MediaPlayer();
        mp2 = new MediaPlayer();

        mp.setOnCompletionListener(this);


        list = (ListView)findViewById(R.id.list);
        //list.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 

        _context=this;





        listTest = new ArrayList<String>( );
        listSoundNames=new ArrayList<String>();

        play = (ImageButton)findViewById(R.id.play);
        back = (ImageButton)findViewById(R.id.prev);
        next = (ImageButton)findViewById(R.id.next);

        //adding listeners
        play.setOnClickListener(this);
        back.setOnClickListener(this);
        next.setOnClickListener(this);


        //action bar controls
        bar = getActionBar();
        bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
        //bar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent))); 

        EditText editText = new EditText(getApplicationContext());
        getActionBar().setCustomView(editText);


        //bar.setDisplayShowTitleEnabled(true);
        //bar.setDisplayHomeAsUpEnabled(true);

        Scanner("/sdcard/");///storage path


        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        if(listTest.size() != 0)
        
            //listAdapter = new ArrayAdapter<String> (MainActivity.this,R.layout.simplerow, listSoundNames);

            ListAdapter listAdapter=new ListAdapter(_context,listSoundNames);
            list.setAdapter(listAdapter);
            list.setOnItemClickListener(new OnItemClickListener() 
            
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
            
                ///////////////////changing list item background on click///////////////////

                list.clearChoices();
                //list.setSelection(position);
                view.setSelected(true);  ///////////////////PROBLEM/////////////

                for(int a = 0; a < parent.getChildCount(); a++)
                

                    parent.getChildAt(a).setBackgroundColor(Color.BLACK);


                


                view.setBackgroundColor(Color.RED);


                ////////////////////////////////////////////////////////////////////////////
                //accessing song path
                String selected = listTest.get(position);
                list.setItemChecked(position, true);//

                //accessing the song name
                String name = (String) ((TextView) view).getText();
                title = name;
                //bar.setTitle(title);
                //Log.e(TAG, name);

                Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
                try
                    mp.reset();
                    mp.setDataSource(listTest.get(position));//source
                    mp.prepare();
                    mp.start();
                    index = position;
                    play.setImageResource(R.drawable.pause);
                    
                catch(Exception e)e.printStackTrace();



            


            );




            

        



        ////////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////*Songs added here to list*////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////

        private void Scanner(String path) 
            // TODO Auto-generated method stub
            
                try 
                
                        File fl = new File(path);
                        File[] listOfFiles = fl.listFiles();              

                        for (File listOfFile : listOfFiles)
                         
                            String s = listOfFile.getName();

                            if(s.endsWith(".mp3"))
                            

                            songpath = listOfFile.getPath();
                            listTest.add(songpath);//adding song names to list
                            //listTest.toString().replaceFirst(songpath, s);



                            // store file name in listSoundNames
                            int pos = s.lastIndexOf(".");
                            if (pos > 0)
                            
                                song = s.substring(0, pos);
                            
                            listSoundNames.add(song);

                            


                            /////////////////////////////////
                            File f = new File(path+s+"/");
                            if (f.exists() && f.isDirectory()) 
                            Scanner(path+s+"/");
                            
                            ////////////////////////////////


                        



                
            catch (Exception e)  
            

            








    @Override
    public void onClick(View v) 
        // TODO Auto-generated method stub

        if (v.equals(play))
        
            if(mp.isPlaying())
            
                mp.pause();
                Toast.makeText(MainActivity.this, "paused", Toast.LENGTH_SHORT).show();
                //change in button image//
                play.setImageResource(R.drawable.play);

            
            else
            
                mp.start();
                Toast.makeText(MainActivity.this, "started", Toast.LENGTH_SHORT).show();
                //change in button image//
                play.setImageResource(R.drawable.pause);
                //
            
        


            if (v.equals(back))
            
                mp.stop();
                mp.reset();
                //bar.setTitle(song);
                if(index!=0)
                
                index = index -1;
                
                else
                
                    index = (list.getAdapter().getCount()-1)-1;

                

                Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
                try 


                    mp.setDataSource(getApplicationContext(), uri);//setting new data source 


                 catch (IllegalArgumentException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                 catch (SecurityException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                 catch (IllegalStateException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
                 catch (IOException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                

                try 
                    mp.prepare();
                 catch (IllegalStateException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                 catch (IOException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                        
                mp.start();//PROBLEM: NOT PLAYING
                Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();

            


            if (v.equals(next))
            

                mp.stop();
                mp.reset();
                index = index +1;


                Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song

                try 


                    mp.setDataSource(getApplicationContext(), uri);//setting new data source 


                 catch (IllegalArgumentException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                 catch (SecurityException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                 catch (IllegalStateException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
                 catch (IOException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                

                try 
                    mp.prepare();
                 catch (IllegalStateException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                 catch (IOException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                        
                mp.start();//PROBLEM: NOT PLAYING
                Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();


            


    


    @Override
    public void onCompletion(MediaPlayer arg0) 
        // TODO Auto-generated method stub
        play.setImageResource(R.drawable.play);
    

    /*@Override
    protected void onStop() 
        super.onStop();
        mp.stop();
        Toast.makeText(getApplicationContext(), "stopped", Toast.LENGTH_LONG).show();

    */

    //////////////////////////////////////////Search box/////////////////////////////////////////////////////

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);



         SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
            SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();

                searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
                searchView.setIconifiedByDefault(false);   
                searchView.setQueryHint(Html.fromHtml(("<font color = #ffffff>"+"Listen Now"+"</font>")));



            SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() 
            
                @Override
                public boolean onQueryTextChange(String newText) 
                
                    // this is your adapter that will be filtered
                    adapter.getFilter().filter(newText);

                    Toast.makeText(getApplicationContext(), "type"+newText, Toast.LENGTH_SHORT).show();
                    return true;
                
                @Override
                public boolean onQueryTextSubmit(String query) 
                
                    // this is your adapter that will be filtered
                    adapter.getFilter().filter(query);

                    //Toast.makeText(getApplicationContext(), query, Toast.LENGTH_SHORT).show();

                    try 
                    
                            File fl = new File("/sdcard/");
                            File[] listOfFiles = fl.listFiles();  
                            String selectedPath="";

                            for (File listOfFile : listOfFiles)
                             
                                String s = listOfFile.getName();

                                if(s.equalsIgnoreCase(query) && s.endsWith(".mp3"))
                                

                                    selectedPath= listOfFile.getPath();//not receiving the path:PROBLEM:HOLDING THE POSITION FOR LIST ITEM


                                //listTest.add(songpath);//adding song names to list
                                //listTest.toString().replaceFirst(songpath, s);
                                Toast.makeText(getApplicationContext(), listOfFile.getPath(), Toast.LENGTH_SHORT).show();

                                /*mp.setDataSource(selectedPath);
                                mp.prepare();
                                mp.start();*/

                                



                                /////////////////////////////////
                                File f = new File("/sdcard/"+s+"/");
                                if (f.exists() && f.isDirectory()) 
                                Scanner("/sdcard/"+s+"/");
                                
                                ////////////////////////////////


                            



                    

                catch (Exception e)  

                    return true;
                
            ;
            searchView.setOnQueryTextListener(textChangeListener);



            return super.onCreateOptionsMenu(menu);

    



【问题讨论】:

【参考方案1】:

这个问题的原因是 Android 回收 ListView 项目的方式。防止这种情况发生的一种方法是手动保存单击的项目。在您的适配器中,您可以创建一个变量来保存当前选定的项目。在您的getView 中,您必须检查当前项目是否与所选项目相同。它看起来像这样:

if(row==currentSelected) //set background color else //another background color -> this is important otherwise all listview items will have the same background color after swiping up and down

【讨论】:

如何在适配器类中获取该值?对不起,如果我听起来很愚蠢,我是新的观众,所以还不是这些方面的大师.. @Sri 如果我理解正确,您希望 currentSelected 在另一个类中。如果是这种情况,您可以为变量创建一个 getter,例如:public View getCurrentView() return currentView 。如果我理解错了,请告诉我 我的意思是你说我应该在列表适配器类中创建一个变量来保存当前选定项的值,但是我在mainactivity中实现了onclick,那么如何在列表适配器中获取该值 那么它正好相反。在定义 onclick 的类中创建一个 getter。确保在构造函数中将该类传递给适配器,以便您可以访问它。【参考方案2】:

你好,试试这个。

1- 您的活动从 ListActivity 扩展。 2-创建下一个适配器 对于您的列表,您可以在 Activity 中创建此适配器:

private class MyAdapter extends BaseAdapter 
@Override
public int getCount() 
    return items.length;


@Override
public String getItem(int position) 
    return items[position];


@Override
public long getItemId(int position) 
    return items[position].hashCode();




@Override
public View getView(int position, View convertView, ViewGroup container) 
    if (convertView == null) 
        convertView = getLayoutInflater().inflate(R.layout.list_item,             

container, false);
    

        ((TextView) convertView.findViewById(android.R.id.text1))
                .setText(getItem(position));

        ImageView imageView = (ImageView)                                                                                 a     convertView.findViewById(R.id.imageView_Icon);
   imageView.setImageResource(imagesId[position]);

        return convertView;
    

items = 包含文本项的数组字符串。 imagesId = 数组 图片在你的draweable中的ID。

在布局中创建下一个 list_item.xml

<com.Test.CheckableLinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_
    android:layout_
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    android:minHeight="?android:listPreferredItemHeight"
    android:gravity="center_vertical">


    <ImageView
        android:id="@+id/imageView_Icon"
        android:layout_
        android:contentDescription="IconDescription"
        android:layout_ />

    <TextView android:id="@android:id/text1"
        android:duplicateParentState="true"
        android:layout_
        android:layout_weight="1"
        android:layout_
        android:textAppearance="?android:textAppearanceMedium"
        android:textColor="@color/hideable_text_color" />


    <ImageView android:src="@drawable/ic_hideable_item"
        android:duplicateParentState="true"
        android:layout_
        android:layout_
        android:layout_marginLeft="16dp"
        android:id="@+id/imageView1" />

</com.Test.CheckableLinearLayout>

在 ListView 中的 Activity 集适配器中:

 ListView listTest = (ListView) findViewById(R.id.listTest);
        listTest .setAdapter(new MyAdapter());

如果您需要最佳示例,请转到 Import Sample -> 选择您的版本 y 转到列表,这里是列表多选的 excelente 示例。

【讨论】:

你为什么使用数组? 您可以使用其他类型的列表,同时让自己获得位置。

以上是关于ListView 项目在滚动后保持突出显示的主要内容,如果未能解决你的问题,请参考以下文章

选择其他按钮时,ListView 突出显示所选项目颜色不会保持不变

Android ListView 所选项目保持突出显示

为啥在recyclerview android中滚动后突出显示的项目丢失

Android - 禁用 ListView 选择突出显示但保持启用 OnClick [重复]

Android ListView 突出显示会导致奇怪的行为

在android的listview中突出显示所选项目