我正在參加考勤應用。該應用程序有ListActivity
由學生列表組成。我想改變顏色爲紅色和綠色表示缺席和呈現。問題是如果我有很長的學生名單而不是屏幕。當前視圖中向下或向上的項目會丟失顏色。我的方法是否正確?如何保存每個單獨列表項目的顏色。當然,如果除了使用ListView
之外還有其他最好的方法,我願意接受建議。如何切換ListView項目顏色並保存?
下面是一個包含列表
public class ListActivity extends Activity implements Serializable{
private String userName;
private TextView nameTextView;
private ListView nameList;
private CustomAdapter adapter;
private boolean colorRed;
private Class myClass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
myClass = new Class();
colorRed = false;
// Open the students list from file if exists
openFromFile();
nameList = (ListView) findViewById(R.id.nameListView);
nameTextView = (TextView) findViewById(R.id.nameTextView);
Bundle extras = getIntent().getExtras();
if (extras != null) {
userName = extras.getString("NAME");
nameTextView.setText("Hi! " + userName);
}
adapter = new CustomAdapter(this, myClass.getStudentNames());
nameList.setAdapter(adapter);
TextView tv = (TextView) findViewById(R.id.sNametv);
nameList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
if (colorRed == true) {
view.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.colorPresent));
colorRed = false;
} else {
view.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.colorAbsent));
colorRed = true;
}
// ALso could use this
// adapterView.getChildAt(position).setBackgroundColor(Color.RED);
}
});
}
我使用的是boolean colorRed
檢查顏色,我無法看到的顏色與顏色從colors xml
比較ListActivity。
nameList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
if (colorRed == true) {
view.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.colorPresent));
colorRed = false;
} else {
view.setBackgroundColor(ContextCompat.getColor(getBaseContext(), R.color.colorAbsent));
colorRed = true;
}
}
});
CustomAdapter班的ListView
public class CustomAdapter extends ArrayAdapter<String> {
public CustomAdapter(Context context, ArrayList<String> names) {
super(context, R.layout.custom_layout, names);
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View customView = inflater.inflate(R.layout.custom_layout, parent, false);
String singleName = getItem(position);
TextView tv = (TextView) customView.findViewById(R.id.sNametv);
tv.setText(singleName);
return customView;
}
}
我仔細檢查過這是一個獨特的問題!放心......
預先感謝您
你正在使用POJO模型類嗎? –
請明確! –
如果您使用模型類來查看列表項,那麼您可以爲每個項目設置另一個整數值,並將其值設置爲1或0.然後在getView方法中檢查該值並根據顏色更改顏色。 –