How to set specific items in spinner to disabled state - android

I've currently managed to disable my spinner if a specific item is selected, however I also want to set that specific item to a disabled state visually. Is this possible?
EDIT: To clarify, when I click on my spinner, I see a drop down menu with several items I can select. I want the disabled items to have a different visual, like in the link above.
private static final String[]paths = {"None", "Arrow Rain", "Restoration", "Ares' Fervor", "Windstorm", "Guardian Angel", "Meteor", "Disaster", "Ares' Frenzy", "Phoenix Flight", "Snowstorm"};
ArrayAdapter<String>adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,paths) {
#Override
public boolean isEnabled(int position) {
global1 = position;
if( (global1 == global2 || global1 == global3 || global1 == global4) && global1>0 ){
return false;
}else{
g1t.setText( "Price: " + String.valueOf(g1p) +"\n" );
totalprice.setText( "Total Price: " + String.valueOf(g1p+g2p+g3p+g4p));
return true;
}
}
};
magic1 = (Spinner)findViewById(R.id.spinnermagic1);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
magic1.setAdapter(adapter1);
magic1.setOnItemSelectedListener(this);
//global 2, 3, and 4 are also positions.
//Is there a way to set those to disabled states?

// Create spinner month, and disable month < today
List<CharSequence> listMonth = new ArrayList<CharSequence>();
for (int m = 0; m < 12; m++) {
if (m < 9) {
listMonth.add("0" + (m + 1));
} else {
listMonth.add("" + (m + 1));
}
}
// Create spinner item
adapterMonth = new ArrayAdapter<CharSequence>(this,
R.layout.layout_spinner_item, listMonth) {
// Disable click item < month current
#Override
public boolean isEnabled(int position) {
// TODO Auto-generated method stub
if (year <= max_year && position < max_month - 1) {
return false;
}
return true;
}
// Change color item
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View mView = super.getDropDownView(position, convertView, parent);
TextView mTextView = (TextView) mView;
if (year <= max_year && position < max_month - 1) {
mTextView.setTextColor(Color.GRAY);
} else {
mTextView.setTextColor(Color.BLACK);
}
return mView;
}
};
adapterMonth
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn2.setAdapter(adapterMonth);

Related

Scrolling the ListView sets colors to all the buttons that do not satisfy the conditions in getview method of SimpleAdapter

I have implemented a ListView using SimpleAdapter in Android. I have set certain conditions in the getView method of the SimpleAdapter.
According to the satisfied conditions the Buttons present in each row of the ListView will be turned to Red, Green, Yellow or Orange.
The problem I am encountering is that when I scroll the ListView up and down continously I can see that some Buttons that don't satisfy the conditions are also changing the colors and at the end all the Buttons have the above mentioned color.
Can anyone suggest me where I am going wrong.My codes are as below:
BaseAdapter waiter_adapter = new SimpleAdapter(
getApplicationContext(), list_details_from_db,
R.layout.waiter_screen_details/* waiter_order_details */,
new String[] { "table_no", "order_id" }, new int[] {
R.id.tv_table_no, R.id.order_id }) {
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
/*final*/ View v = super.getView(position, convertView,
parent);
// Log.i("key values sub id in get view ",
// ""+key_names);
final TextView order_id = (TextView) v
.findViewById(R.id.order_id);
Log.i("Order id check from getview ", order_id
.getText().toString());
Button bt_waiter_id = (Button) v
.findViewById(R.id.bt_waiter_id);
Button placed_id = (Button) v
.findViewById(R.id.placed_id);
Button confirmed = (Button) v
.findViewById(R.id.confirmed);
Button prepared = (Button) v
.findViewById(R.id.prepared);
prepared.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String o_id = order_id.getText().toString();
Intent prep_list = new Intent(
Waiter_Order_List_ctivity.this,
Prep_List_activity.class);
prep_list.putExtra("Order_Id", o_id
/* order_id_to_intent */);
Log.i("Order id sent to Prep list", o_id /* order_id_to_intent */);
startActivity(prep_list);
}
});
confirmed.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
final String order_id_str = order_id.getText()
.toString();
ArrayList<HashMap<String, String>> data = db
.get_order_course_list(order_id_str);
ArrayList<HashMap<String, String>> c = db
.get_item_status(order_id_str);
// if(item_status_from_db.get(index))
Log.i("item status retrievd from db", "" + c);
Log.i("database retrieved values from order course list",
"" + data);
Log.i("data size", "" + data.size());
try {
placed_id.setText(data.get(0).get("ist"));
confirmed.setText(data.get(0).get("confirm_ist"));
} catch (Exception e) {
e.printStackTrace();
}
try {
count = 0;
count_confirmed = 0;
count_processed = 0;
if (list_details_from_db.get(position)
.get("status")
.compareToIgnoreCase("Initial") == 0) {
bt_waiter_id.setBackground(getResources()
.getDrawable(
R.drawable.waitr_ordr_red_btn));
bt_waiter_id.setText("Waiter Id:"
+ "\n"
+ list_details_from_db.get(position)
.get("initial_status"));
} else {
for (int i = 0; i < data.size(); i++) {
String status_str = data.get(i).get(
"status1");
if (status_str
.compareToIgnoreCase("Placed") == 0) {
count++;
}
if (status_str
.compareToIgnoreCase("Confirmed") == 0) {
count_confirmed++;
}
if (status_str
.compareToIgnoreCase("Processed") == 0) {
count_processed++;
}
}
}
if (count > 0) {
placed_id
.setBackground(getResources()
.getDrawable(
R.drawable.waitr_ordr_yellow_btn));
}
if (count_confirmed > 0) {
confirmed
.setBackground(getResources()
.getDrawable(
R.drawable.waitr_ordr_orange_btn));
/*
* confirmed
* .setOnClickListener(Waiter_Order_List_ctivity
* .this);
*/
}
if (count_processed > 0) {
prepared.setBackground(getResources()
.getDrawable(
R.drawable.waitr_ordr_green_btn));
/*
* prepared.setOnClickListener(
* Waiter_Order_List_ctivity.this);
*/
}
if (c.size() > 0) {
prepared.setBackground(getResources()
.getDrawable(
R.drawable.waitr_ordr_green_btn));
}
} catch (Exception e) {
e.printStackTrace();
}
placed_id
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intTableItm = new Intent(
Waiter_Order_List_ctivity.this,
Waiter_Confirm.class);
intTableItm.putExtra("Order_Id",
order_id_str);
startActivity(intTableItm);
}
});
return v;
}
};
w_order_list.setAdapter(waiter_adapter);
This depends on the reusage of the Listitems. If you change the Background in the if condition:
if (list_details_from_db.get(position)
You have to set it to the default background in the else condition.
//edit
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
/*final*/ View v = super.getView(position, convertView,
parent);
// Log.i("key values sub id in get view ",
// ""+key_names);
final TextView order_id = (TextView) v
.findViewById(R.id.order_id);
Log.i("Order id check from getview ", order_id
.getText().toString());
Button bt_waiter_id = (Button) v
.findViewById(R.id.bt_waiter_id);
Button placed_id = (Button) v
.findViewById(R.id.placed_id);
Button confirmed = (Button) v
.findViewById(R.id.confirmed);
Button prepared = (Button) v
.findViewById(R.id.prepared);
placed_id.setText("Your standard value");
confirmed.setText("Your standard value");
placed_id.setBackground(getResources()
.getDrawable(
R.drawable.your_standard_drawable));
confirmed.setBackground(getResources()
.getDrawable(
R.drawable.your_standard_drawable));
prepared.setBackground(getResources()
.getDrawable(
R.drawable.your_standard_drawable));
bt_waiter_id.setBackground(getResources()
.getDrawable(
R.drawable.your_standard_drawable));
bt_waiter_id.setText("your standard value");
//
//[...] Rest of your code
}

Android how to set color of specific item in GridView

I have a GridView with an Adapter that creates a Calendar to show some events from my web server.
The data loads succesfully and when an item is clicked it shows the event. The thing is that i need to know which days have an event by setting up the background color of the item whithout the need of clicking them.
How can i achieve that?
This is the Adapter code:
public class CalendarAdapter extends BaseAdapter {
private Context mContext;
private java.util.Calendar month;
public GregorianCalendar pmonth; // calendar instance for previous month
/**
* calendar instance for previous month for getting complete view
*/
public GregorianCalendar pmonthmaxset;
private GregorianCalendar selectedDate;
int firstDay;
int maxWeeknumber;
int maxP;
int calMaxP;
int lastWeekDay;
int leftDays;
int mnthlength;
String itemvalue, curentDateString;
DateFormat df;
private ArrayList<String> items;
public static List<String> dayString;
private View previousView;
public CalendarAdapter(Context c, GregorianCalendar monthCalendar) {
CalendarAdapter.dayString = new ArrayList<String>();
Locale.setDefault(Locale.US);
month = monthCalendar;
selectedDate = (GregorianCalendar) monthCalendar.clone();
mContext = c;
month.set(GregorianCalendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<String>();
df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
curentDateString = df.format(selectedDate.getTime());
refreshDays();
}
public void setItems(ArrayList<String> items) {
for (int i = 0; i != items.size(); i++) {
if (items.get(i).length() == 1) {
items.set(i, "0" + items.get(i));
}
}
this.items = items;
}
public int getCount() {
return dayString.size();
}
public Object getItem(int position) {
return dayString.get(position);
}
public long getItemId(int position) {
return 0;
}
// create a new view for each item referenced by the Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
LayoutInflater vi = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.calendar_item, null);
}
dayView = (TextView) v.findViewById(R.id.date);
// separates daystring into parts.
String[] separatedTime = dayString.get(position).split("-");
// taking last part of date. ie; 2 from 2012-12-02
String gridvalue = separatedTime[2].replaceFirst("^0*", "");
// checking whether the day is in current month or not.
if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
// setting offdays to white color.
dayView.setTextColor(Color.WHITE);
dayView.setClickable(false);
dayView.setFocusable(false);
} else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
dayView.setTextColor(Color.WHITE);
dayView.setClickable(false);
dayView.setFocusable(false);
} else {
// setting curent month's days in blue color.
dayView.setTextColor(Color.BLUE);
}
if (dayString.get(position).equals(curentDateString)) {
setSelected(v);
previousView = v;
} else {
v.setBackgroundResource(R.drawable.list_item_background);
}
dayView.setText(gridvalue);
// create date string for comparison
String date = dayString.get(position);
if (date.length() == 1) {
date = "0" + date;
}
String monthStr = "" + (month.get(GregorianCalendar.MONTH) + 1);
if (monthStr.length() == 1) {
monthStr = "0" + monthStr;
}
// show icon if date is not empty and it exists in the items array
ImageView iw = (ImageView) v.findViewById(R.id.date_icon);
if (date.length() > 0 && items != null && items.contains(date)) {
iw.setVisibility(View.VISIBLE);
} else {
iw.setVisibility(View.INVISIBLE);
}
Log.e("color",""+CalendarView.color);
if (CalendarView.color.equals("YELLOW")){
v.setBackgroundColor(Color.YELLOW);
}else if (CalendarView.color.equals("RED")){
v.setBackgroundColor(Color.RED);
}
return v;
}
public View setSelected(View view) {
if (previousView != null) {
previousView.setBackgroundResource(R.drawable.list_item_background);
}
previousView = view;
view.setBackgroundResource(R.drawable.calendar_cel_selectl);
return view;
}
public void refreshDays() {
// clear items
items.clear();
dayString.clear();
Locale.setDefault(Locale.US);
pmonth = (GregorianCalendar) month.clone();
// month start day. ie; sun, mon, etc
firstDay = month.get(GregorianCalendar.DAY_OF_WEEK);
// finding number of weeks in current month.
maxWeeknumber = month.getActualMaximum(GregorianCalendar.WEEK_OF_MONTH);
// allocating maximum row number for the gridview.
mnthlength = maxWeeknumber * 7;
maxP = getMaxP(); // previous month maximum day 31,30....
calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
/**
* Calendar instance for getting a complete gridview including the three
* month's (previous,current,next) dates.
*/
pmonthmaxset = (GregorianCalendar) pmonth.clone();
/**
* setting the start date as previous month's required date.
*/
pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);
/**
* filling calendar gridview.
*/
for (int n = 0; n < mnthlength; n++) {
itemvalue = df.format(pmonthmaxset.getTime());
pmonthmaxset.add(GregorianCalendar.DATE, 1);
dayString.add(itemvalue);
}
}
private int getMaxP() {
int maxP;
if (month.get(GregorianCalendar.MONTH) == month
.getActualMinimum(GregorianCalendar.MONTH)) {
pmonth.set((month.get(GregorianCalendar.YEAR) - 1),
month.getActualMaximum(GregorianCalendar.MONTH), 1);
} else {
pmonth.set(GregorianCalendar.MONTH,
month.get(GregorianCalendar.MONTH) - 1);
}
maxP = pmonth.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
return maxP;
}
}
Thanks in advance
Calendar_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/calendar_cell"
android:gravity="center"
android:orientation="vertical"
android:padding="2dip" >
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#0000D7"
android:textSize="14dip"
android:textStyle="bold" >
</TextView>
<ImageView
android:id="#+id/date_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/date"
android:src="#drawable/dot"
android:visibility="gone" />
</LinearLayout>
You can set the background color for the required Grid Item depending on the item position
row.setBackgroundColor(Color.GREEN);
But due to the GridView item view recycle , you will see the same background color set to some other items too.(since the view instance is same , only the data is different)
To fix this, you need to let GridView know that you have two different type of views ( one with color and other without color)
First Override getViewTypeCount and inform GridView that you have two view types
#Override
public int getViewTypeCount() {
return 2;
}
Next, Override getItemViewType and let GridView know that which items position type is different. e.g., if the items 1 and 3 has events then return 1(some unique number) for those position and return 0 for other positions
#Override
public int getItemViewType(int position){
// return a unique number
if(position == 1 || position == 3){
return 1;
}
else {
return 0;
}
}
Finally, when getView is called. check for the position and set background color only for those specific items
if(position == 1 || position == 3){
row.setBackgroundColor(Color.GREEN);
}
This should work. perfectly. Let me know.
get the id of your inflator parent layout and set like below:
LinearLayout f_l = (LinearLayout) itemView.findViewById(R.id.pr_bg);
if (position % 3 == 0) {
f_l.setBackgroundResource(R.drawable.campaignbase_black);
} else if (position % 3 == 1) {
f_l.setBackgroundResource(R.drawable.campaignbase_pink);
} else if (position % 3 == 2) {
f_l.setBackgroundResource(R.drawable.campaignbase_brown);
}

How to get checked items from android listview?

I have an android application which uses listview.Each row consist of ImageView,a TextView and a CheckBox.
I want to get selected items from this listview.I used
private void getSelectedItems() {
List<String>list = new ArrayList<String>();
try {
SparseBooleanArray checkedItems = new SparseBooleanArray();
checkedItems = listView.getCheckedItemPositions();
if (checkedItems == null) {
return;
}
final int checkedItemsCount = checkedItems.size();
for (int i = 0; i < checkedItemsCount; ++i) {
int position = checkedItems.keyAt(i);
boolean bool = checkedItems.valueAt(position);
if (bool) {
list.add(mainList.get(position));
}
}
} catch (Exception e) {
}
}
But i want to set some items as checked with respect to a condition at start up.The checked item obtain only when if the user check/Uncheck an item.No checked item obtain even if the item is set as checked at the start up programmatically.What is the problem here?
Thanks in Advance
Do something like this,
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
myListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long arg3) {
CheckBox cb = (CheckBox) view.findViewById(R.id.yourCheckBox);
Toast.makeText(getApplicationContext(), "Row " + position + " is checked", Toast.LENGTH_SHORT).show();
if (cb.isChecked()) {
checkedPositions.add(position); // add position of the row
// when checkbox is checked
} else {
checkedPositions.remove(position); // remove the position when the
// checkbox is unchecked
Toast.makeText(getApplicationContext(), "Row " + position + " is unchecked", Toast.LENGTH_SHORT).show();
}
}
});

Contextual action mode in SherlockListFragment: Item isn't selected and I can't select several items

My problem is when I select an item and I release the item isn't selected and the first time that I do click there isn't checked elements.
Code:
public class SongsFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Cursor>, OnItemLongClickListener {
...
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
mMode = null;
mListView = getListView();
mListView.setItemsCanFocus(false);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mListView.setOnItemLongClickListener(this);
}
...
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(getClass().getSimpleName(), "longClick");
SparseBooleanArray checked = mListView.getCheckedItemPositions();
if(checked.size() == 0)
Log.d(getClass().getSimpleName(), "checked size 0");
boolean hasCheckedElement = false;
for (int i = 0; i < checked.size() && !hasCheckedElement; i++) {
Log.d(getClass().getSimpleName(), "For: " + Integer.toString(i));
hasCheckedElement = checked.valueAt(i);
}
if (hasCheckedElement) {
Log.d(getClass().getSimpleName(),"hasCheckedElement");
if (mMode == null) {
mMode = getSherlockActivity().startActionMode(
mActionModeCallback);
}
} else {
Log.d(getClass().getSimpleName(),"!!!hasCheckedElement");
if (mMode != null) {
mMode.finish();
}
}
return false;
}
...
}
For example: do click on a item, release, do click on the same item. This is the output:
SongsFragment(16560): longClick
SongsFragment(16560): checked size 0
SongsFragment(16560): !!!hasCheckedElement
SongsFragment(16560): longClick
SongsFragment(16560): For: 0
SongsFragment(16560): hasCheckedElement
Why the first time isn't checked?
Why the item isn't selected when I release?
Thanks.
I found this tutorial (in spanish): http://androcode.es/2012/03/seleccion-individualmultiple-de-elementos-en-un-listview/
Now all it's working.

Android calendar event use gridview listview

http://i.imgur.com/PyO4q.png?1
This image is using the gridview to make a calendar, but now I want to add a new event in "day". So I thought to use the listview inside the gridview-day, but the problem is the listview doesn't scroll. I think maybe the listview scroll collides with gridview. Please give me some idea to solve this problem.
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView dayView;
TextView present;
TextView meeting;
TextView other;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.calendar_item, null);
}
dayView = (TextView)v.findViewById(R.id.date);
present=(TextView)v.findViewById(R.id.ptextView1);
meeting=(TextView)v.findViewById(R.id.mtextView2);
other=(TextView)v.findViewById(R.id.otextView3);
// listitem=(ListView)v.findViewById(R.id.calendarlist);
// listitem.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
// disable empty days from the beginning
if(days[position].equals("")) {
dayView.setClickable(false);
dayView.setFocusable(false);
}
else {
// mark current day as focused
if(month.get(Calendar.YEAR)== selectedDate.get(Calendar.YEAR) && month.get(Calendar.MONTH)== selectedDate.get(Calendar.MONTH) && days[position].equals(""+selectedDate.get(Calendar.DAY_OF_MONTH))) {
v.setBackgroundResource(R.drawable.item_background_focused);
}
else {
v.setBackgroundResource(R.drawable.list_item_background);
}
}
dayView.setText(days[position]);
present.setVisibility(View.GONE);
meeting.setVisibility(View.GONE);
other.setVisibility(View.GONE);
for(int t=0;t<date1.size();t++){
if(returndouble(dayView.getText().toString()).equals(date1.get(t).get(3))){
if(date1.get(t).get(1).equals("Presented")){
meeting.setVisibility( View.VISIBLE);
}else if(date1.get(t).get(1).equals("Present")){
present.setVisibility( View.VISIBLE);
}else{
other.setVisibility( View.VISIBLE);
}
}
}
// create date string for comparison
String date = days[position];
if(date.length()==1) {
date = "0"+date;
}
String monthStr = ""+(month.get(Calendar.MONTH)+1);
if(monthStr.length()==1) {
monthStr = "0"+monthStr;
}
// show icon if date is not empty and it exists in the items array
// ImageView iw = (ImageView)v.findViewById(R.id.date_icon);
/* if(date.length()>0 && items!=null && items.contains(date)) {
iw.setVisibility(View.VISIBLE);
}
else {
iw.setVisibility(View.INVISIBLE);
}*/
return v;
}
public void refreshDays()
{
// clear items
items.clear();
Calendardb date=new Calendardb(mContext);
date1= date.calendarselect(String.valueOf( month.get(Calendar.YEAR))+"/"+returndouble(String.valueOf((month.get(Calendar.MONTH)+1))));
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay = (int)month.get(Calendar.DAY_OF_WEEK);
// figure size of the array
if(firstDay==1){
days = new String[lastDay+(FIRST_DAY_OF_WEEK*6)];
}
else {
days = new String[lastDay+firstDay-(FIRST_DAY_OF_WEEK+1)];
}
int j=FIRST_DAY_OF_WEEK;
// populate empty days before first real day
if(firstDay>1) {
for(j=0;j<firstDay-FIRST_DAY_OF_WEEK;j++) {
days[j] = "";
}
}
else {
for(j=0;j<FIRST_DAY_OF_WEEK*6;j++) {
days[j] = "";
}
j=FIRST_DAY_OF_WEEK*6+1; // sunday => 1, monday => 7
}
// populate days
int dayNumber = 1;
for(int i=j-1;i<days.length;i++) {
days[i] = ""+dayNumber;
dayNumber++;
}
}

Categories

Resources