gpt4 book ai didi

java - 使用数组设置一周的第一天

转载 作者:行者123 更新时间:2023-12-01 16:33:24 24 4
gpt4 key购买 nike

我有一个字符串数组,其中包含工作日的名称:

private final String[] weekdays = new String[]{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};

我默认将星期一设置为一周的第一天。

现在,我为用户提供了选择是否要将星期日或星期一设置为一周的第一天的选项:

if (firstDay == 0) {
holder.txtWeekdays.setText(weekdays[position]);
}

使用相同的字符串数组,如何将星期日设置为一周的第一天?

else {
holder.txtWeekdays.setText(weekdays[position]-1); //this returns an error
}

更新代码:

public class CalendarWeekAdapter extends BaseAdapter{

private final String[] weekdays = new String[]{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
Context mContext;

private LayoutInflater mInflater;
public CalendarWeekAdapter(Context c)
{
mContext=c;
mInflater = LayoutInflater.from(c);
}
public int getCount()
{
return weekdays.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder=null;
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.calendar_week_gridcell, parent,false);
holder = new ViewHolder();
holder.txtWeekdays=(TextView)convertView.findViewById(R.id.weekdays);
if(position==0)
{
convertView.setTag(holder);
}
}
else
{
holder = (ViewHolder) convertView.getTag();
}

if (firstDay == 0) {
holder.txtWeekdays.setText(weekdays[position]);
}
else {
holder.txtWeekdays.setText(weekdays[position]);
}

return convertView;
}

}
static class ViewHolder
{
TextView txtWeekdays;
}

最佳答案

您正在尝试从字符串中减 1。这实际上是行不通的。

您需要做的是创建一个返回星期几的方法。像这样的事情:

public String getDayOfWeek(int day, int firstDay) {
String[] weekdays;
if (firstDay == 0)
weekdays = new String[]{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
else
weekdays = new String[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
return weekdays[day];
}

现在,您可以按位置执行此操作(使用 weekdays[position - 1]),但上述内容将帮助您避免代码中的错误(例如索引 -1),并为您提供更清楚地了解返回的内容。

关于java - 使用数组设置一周的第一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12010593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com