public class MainActivity extends AppCompatActivity {
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=(ListView) findViewById(R.id.listview);
String[] months={"January","Feburary","March","April","May","June","July","August","September","October","November","December"};
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,android.R.id.text1,months);
list.setAdapter(adapter);
//i want here to use the positions of rows of listview
//Actually i want that whenever activity open, background color of odd listview items should be of black color and even should be of white background color.
//with simple adapter and without using any click listener.
}
}
您所需要的只是getItemViewType,它允许您在recyclerview中夸大多个视图。
在您的适配器中,您可以写:
//Returns the view type of the item at position for the purposes of view recycling.
@Override
public int getItemViewType(int position) {
if (position%2 == 0) {
//set even color
} else {
//set odd color
}
return -1;
}
尝试这个想法
for ( int i = 0 ; i < listView.getCount() ; i++){
View v = getViewByPosition(i,listView);
// then check if i is odd set background color with what u want
v.setBackgroundColor(Color.Parse("#000000"));
}
public View getViewByPosition(int position, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition =firstListItemPosition +
listView.getChildCount() - 1;
if (position < firstListItemPosition || position > lastListItemPosition ) {
return listView.getAdapter().getView(position,
listView.getChildAt(position), listView);
} else {
final int childIndex = position - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
public class BlackWhiteAdapter extends ArrayAdapter<String> {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
}
String txt = getItem(position);
TextView tvMonth = (TextView) convertView.findViewById(android.R.id.text1);
tvMonth.setTextColor((position%2==0) 0xFF00000 : 0xFFFFFFFF);
return convertView;
}
}
当您在AdapterView上设置Addap()时,例如ListView,在内部调用getView(),并在AdapterView中填充从其返回的视图覆盖getView方法,您可以获得选定的值
String[] months={"January","Feburary","March","April","May","June","July","August","September","October","November","December"};
String selectedMonth ;
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,android.R.id.text1,months){
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View v = super.getView(position, convertView, parent);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectedMonth = months[position];
}
});
return v;
}
};