当前位置: 首页 > 知识库问答 >
问题:

实现Fiterable接口到自定义ArrayAdapter[duplicate]

左丘凡
2023-03-14

歌曲对象的类文件:

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;
        }
    });
}
}
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;
}
}
<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_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.yunfrankzhang.mixtapeofsadness.NowPlayingActivity">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <SearchView
        android:id="@+id/search_msg"
        android:layout_marginTop="8dp"
        android:layout_marginRight="8dp"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Search here"
        android:textSize="16dp"
        android:layout_weight="1"
        android:layout_marginLeft="8dp"/>
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mixTapeList">
</ListView>
</LinearLayout>

共有1个答案

康鹏云
2023-03-14

使适配器能够返回适当的歌曲对象,其专辑名称包含用户在搜索视图中输入的字符串

如果这就是你想要过滤的全部,那么有一个更简单的方法。

向跟踪对象添加ToString()方法

public String getAlbumName(){
    return mAlbumName;
}

@Override
public String toString() {
    return getAlbumName();
}
newTrackAdapter.getFilter().filter("your input");
 类似资料:
  • java代码: 类文章 类自定义适配器: 错误logcat:

  • 不管怎样,关于我的问题:有人愿意编写一个非常、非常、非常、通用、直接和简单的自定义ArrayAdapter,该ArrayAdapter需要两个字符串值,可以与ListView一起使用吗?…或者,尝试调试我的尝试,希望找到我的问题所在。 任何帮助都很感激,谢谢。 我已经包括了我知道需要的代码,但我一直在与其他所有东西罢工。 错误:(20,9)错误:没有为ArrayAdapter找到合适的构造函数(上

  • 我是Spring Boot的新手,所以我有几个基本问题。 当我们定义一个扩展JpaRepostory的Repostory接口时 这些方法可以从 Service 类调用(我们可能甚至不需要提及这两个方法)。到目前为止,一切都很好。 问题: > 方法是如何定义的?它在幕后是如何被称为的? 如果我们想用原生SQL添加一个自定义方法< code>findUserAction呢?在这种情况下,我们需要在<

  • 为了测试它,我创建了一个新的控制器,以避免干扰我正在工作的控制器TesteController2,它运行良好。因此,我的下一步是扩展IStudentRepository中的ICustomRepository,在TesteController2中进行更改,然后Spring将不再找到我的findCustom方法,它尝试将该方法创建为JPA关键字并返回和错误。这是我的存储库接口: 和TesteContr

  • 在自定义arrayAdapter中实现自定义getFilter时遇到问题。实际上,我不知道如何实现它。尝试了各种代码,但仍然没有成功。这是我的自定义阵列适配器。 这是ListTO课程。 这是布局图。 这里的搜索关键字来自“inputSearch”编辑文本。 这是文本更改的侦听器。 谢谢

  • 问题内容: 我解析了.yaml文件,需要以自定义方式解组其属性之一。我正在使用包裹。 有问题的属性按如下方式存储在我的.yaml文件中: 因此,它基本上是一种类型。 但是我需要在哪里定义为: 我的结构: 我试图像这样实现Unmarshaler接口: 我的问题是在函数内部未定义类型,从而在运行时导致nil指针异常。 我如何在此处正确实现Unmarshaler接口? 问题答案: 由于@Volker并未