为自定义 ArrayAdapter 实现 Fiterable 接口
Posted
技术标签:
【中文标题】为自定义 ArrayAdapter 实现 Fiterable 接口【英文标题】:Implementing Fiterable interface to custom ArrayAdapter [duplicate] 【发布时间】:2018-07-17 18:15:18 【问题描述】:我的目标是使用 ArrayAdapter 加载具有 20 首自定义歌曲对象的 ListView,并让适配器能够返回适当的歌曲对象,其专辑名称包含用户在搜索视图中输入的字符串。
到目前为止,20 首歌曲按预期显示,但是过滤器不起作用:searchView 中的更改对应用程序没有任何影响。我尝试将过滤器“约束”设置为硬编码字符串,过滤器也不响应。
歌曲对象的类文件:
public class Track
private String mSongName;
private String mArtistName;
private String mAlbumName;
private int mAlbumRelease;
private int mAlbumArt;
public Track (String artistName, String albumName, String songName, int releaseDate, int imageID)
mArtistName = artistName;
mAlbumName = albumName;
mSongName = songName;
mAlbumRelease = releaseDate;
mAlbumArt = imageID;
public String getArtistName()
return mArtistName;
public String getAlbumName()
return mAlbumName;
public String getSongName()
return mSongName;
public String getReleaseDate()
return Integer.toString(mAlbumRelease);
public int getAlbumArt()
return mAlbumArt;
用于加载包含 20 首歌曲的 ArrayList 的类文件:
public class RecordMixTape
ArrayList<Track> mixTape = new ArrayList<>();
public void record ()
mixTape.add(new Track("Lana del Rey", "Ultraviolence", "Black Beauty", 2014, R.drawable.ultraviolence));
mixTape.add(new Track("Lana del Rey", "Young and Beautiful", "Young and Beautiful", 2013, R.drawable.young_and_beautiful));
mixTape.add(new Track("Childish Gambino", "Redbone", "Redbone", 2016, R.drawable.redbone));
mixTape.add(new Track("Coldplay", "A Head Full Of Dreams", "Fun", 2015, R.drawable.a_head_full_of_dreams));
mixTape.add(new Track("Eminem", "Revival", "Tragic Endings", 2017, R.drawable.revival));
mixTape.add(new Track("Phil Collins", "Face Value", "In The Air Tonight", 1981, R.drawable.face_value));
mixTape.add(new Track("The Beatles", "A Hard Day's Night", "And I Love Her", 1964, R.drawable.a_head_full_of_dreams));
mixTape.add(new Track("Shayne Ward", "Shayne Ward", "That's My Goal", 2006, R.drawable.shayne_ward));
mixTape.add(new Track("Kanye West", "808s & Heartbreak", "Heartless", 2008, R.drawable.kanye_808s_heartbreak));
mixTape.add(new Track("Jay-z & Eminem", "The Blueprint", "Renegade", 2001, R.drawable.the_blueprint));
mixTape.add(new Track("Frank Ocean", "Novacane", "Novacane", 2011, R.drawable.novacane));
mixTape.add(new Track("Pink Floyd", "The Dark Side Of The Moon", "Time", 1973, R.drawable.the_dark_side_of_the_moon));
mixTape.add(new Track("The Antlers", "Hospice", "Kettering", 2009, R.drawable.hospice));
mixTape.add(new Track("Justin Bieber", "Believe", "As Long As You Love Me", 2012, R.drawable.believe));
mixTape.add(new Track("Robbie Williams", "Escapology", "Feel", 2002, R.drawable.escapology));
mixTape.add(new Track("Elton John", "Goodbye Yellow Brick Road", "Candle In The Wind", 1973, R.drawable.goodbye_yellow_brick_road));
mixTape.add(new Track("Michael Jackson", "Off The Wall", "She's Out Of My Life", 1979, R.drawable.off_the_wall));
mixTape.add(new Track("Passenger", "All The Little Lights", "Let Her Go", 2012, R.drawable.all_the_little_lights));
mixTape.add(new Track("Johnny Cash", "Unearthed", "Hurt", 2003, R.drawable.unearthed));
mixTape.add(new Track("Sinead O'Connor", "I Do Not Want What I Haven't Got", "Nothing Compares 2 U", 1990, R.drawable.i_do_not_want_what_i_havent_got));
public ArrayList<Track> getList()
return mixTape;
这里是主要的活动java文件:
public class MainActivity extends AppCompatActivity
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Track> newMixTape = new ArrayList<>();
//instantiate custom RecordMixTape object, and load an ArrayList with 20 Track objects
RecordMixTape myMixTape = new RecordMixTape();
myMixTape.record();
newMixTape = myMixTape.getList();
final TrackAdapter newTrackAdapter = new TrackAdapter(this, newMixTape);
ListView listView = (ListView) findViewById(R.id.mixTapeList);
final SearchView searchMsg = (SearchView) findViewById(R.id.search_msg);
listView.setAdapter(newTrackAdapter);
//have the searchView execute the filter method in the TrackAdapter
searchMsg.setOnQueryTextListener(new SearchView.OnQueryTextListener()
@Override
public boolean onQueryTextSubmit(String query)
newTrackAdapter.getFilter().filter(query);
return false;
@Override
public boolean onQueryTextChange(String query)
newTrackAdapter.getFilter().filter(query);
return false;
);
这是自定义的 ArrayAdapter:
public class TrackAdapter extends ArrayAdapter<Track> implements Filterable
private ArrayList<Track> filteredList = null;
private ArrayList<Track> data = null;
public TrackAdapter(Activity context, ArrayList<Track> trackList)
super(context, 0, trackList);
data = trackList;
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent)
View listItemView = convertView;
if (listItemView == null)
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
final Track currentTrack = getItem(position);
//clone song information to the current convertView
final TextView artistNameField = listItemView.findViewById(R.id.artistName);
artistNameField.setText(currentTrack.getArtistName());
final TextView albumNameField = listItemView.findViewById(R.id.albumName);
albumNameField.setText(currentTrack.getAlbumName());
final TextView songNameField = listItemView.findViewById(R.id.songName);
songNameField.setText(currentTrack.getSongName());
TextView albumReleaseDate = listItemView.findViewById(R.id.releaseDate);
albumReleaseDate.setText(currentTrack.getReleaseDate());
ImageView albumArtView = listItemView.findViewById(R.id.albumArt);
albumArtView.setImageResource(currentTrack.getAlbumArt());
albumArtView.setOnClickListener(new View.OnClickListener()
//intent which triggers another activity
@Override
public void onClick(View view)
Intent playThisTrack = new Intent(getContext(), NowPlayingActivity.class);
playThisTrack.putExtra("index", position);
getContext().startActivity(playThisTrack);
);
return listItemView;
Filter myFilter = new Filter()
@Override
protected FilterResults performFiltering(CharSequence constraint)
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
ArrayList<Track> resultList = new ArrayList<Track>();
for (int i = 0; i < data.size(); i++)
Track item = data.get(i);
if (item.getAlbumName().toLowerCase().contains(filterString))
resultList.add(item);
results.values = resultList;
results.count = resultList.size();
return results;
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results)
filteredList = (ArrayList<Track>) results.values;
notifyDataSetChanged();
;
@Override
public Filter getFilter()
return myFilter;
为了以防万一,这是加载另一个自定义布局文件以显示歌曲的主要活动 xml:
<LinearLayout
android:id="@+id/parent_view"
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_
android:layout_
android:orientation="vertical"
tools:context="com.yunfrankzhang.mixtapeofsadness.NowPlayingActivity">
<LinearLayout
android:layout_
android:layout_
android:orientation="horizontal">
<SearchView
android:id="@+id/search_msg"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_
android:layout_
android:hint="Search here"
android:textSize="16dp"
android:layout_weight="1"
android:layout_marginLeft="8dp"/>
</LinearLayout>
<ListView
android:layout_
android:layout_
android:id="@+id/mixTapeList">
</ListView>
</LinearLayout>
请赐教,我在哪里搞砸了,随意翻阅我的代码。我从心底里感谢你。
【问题讨论】:
你能创建一个最小的例子来演示这个问题吗? ArrayAdapter 对于这种自定义来说是一个糟糕的类......它已经实现了过滤......我会尝试从您的 publishResults 调用oldFilter.publishResults
,其中 oldFilter
通过调用 @987654329 在 Adapter 内部获取@(但我不建议这样做)...在 TrackAdapter 添加字段 private Filter oldFilter = getFilter();
然后在 publishResults
中调用`oldFilter.publishResults(constraint, results)`
@BrunoCarvalhal 问题是 filteredList
从未使用过...
如果专辑名称是从对象中的 toString 方法返回的,那么这个过滤器定义都不需要***.com/a/30416831/2308683
@cricket_007 是的。很好的修复。做了我们想要的,我将研究一个重新填充数据列表的解决方案,以防用户想要进行另一个查询。谢谢板球。
【参考方案1】:
让适配器能够返回适当的歌曲对象,其专辑名称包含用户在搜索视图中输入的字符串
如果这就是您想要过滤的全部内容,还有一种更简单的方法。
将toString()
方法添加到您的 Track 对象
public String getAlbumName()
return mAlbumName;
@Override
public String toString()
return getAlbumName();
那么这将简单地满足您的需求
newTrackAdapter.getFilter().filter("your input");
【讨论】:
以上是关于为自定义 ArrayAdapter 实现 Fiterable 接口的主要内容,如果未能解决你的问题,请参考以下文章
Android中Spinner下拉列表(使用ArrayAdapter和自定义Adapter实现) .
如何使用 SQLite 中的数据实现自定义 ArrayAdapter