您好,登錄后才能下訂單哦!
在Android中,要為GridView實現自定義排序邏輯,你需要創建一個自定義的Comparator
,并在適配器中使用它。以下是一個簡單的示例,展示了如何為GridView實現自定義排序邏輯:
Comparator
。在這個例子中,我們將根據字符串的長度對GridView中的項進行排序: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設置適配器: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);
}
}
現在,你的GridView將根據字符串長度進行自定義排序。你可以根據需要修改CustomComparator
以實現不同的排序邏輯。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。