您好,登錄后才能下訂單哦!
在Android中,要為GridView實現(xiàn)自定義排序邏輯,你需要創(chuàng)建一個自定義的Comparator
,并在適配器中使用它。以下是一個簡單的示例,展示了如何為GridView實現(xiàn)自定義排序邏輯:
Comparator
。在這個例子中,我們將根據(jù)字符串的長度對GridView中的項進(jìn)行排序:import java.util.Comparator;
public class CustomComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}
ArrayAdapter
,并在其中使用自定義的Comparator
:import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CustomArrayAdapter extends ArrayAdapter<String> {
private List<String> originalList;
private List<String> sortedList;
private CustomComparator comparator;
public CustomArrayAdapter(@NonNull Context context, int resource, @NonNull List<String> objects, CustomComparator comparator) {
super(context, resource, objects);
this.originalList = new ArrayList<>(objects);
this.sortedList = new ArrayList<>(objects);
this.comparator = comparator;
Collections.sort(sortedList, comparator);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.grid_item, parent, false);
}
TextView textView = convertView.findViewById(R.id.text_view);
textView.setText(sortedList.get(position));
return convertView;
}
}
CustomArrayAdapter
為GridView設(shè)置適配器:import android.os.Bundle;
import android.widget.GridView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = findViewById(R.id.grid_view);
List<String> items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
items.add("Item 4");
items.add("Item 5");
CustomComparator comparator = new CustomComparator();
CustomArrayAdapter adapter = new CustomArrayAdapter(this, R.layout.grid_item, items, comparator);
gridView.setAdapter(adapter);
}
}
現(xiàn)在,你的GridView將根據(jù)字符串長度進(jìn)行自定義排序。你可以根據(jù)需要修改CustomComparator
以實現(xiàn)不同的排序邏輯。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。