How manage multichoice list in ListView with toolbar in fragmentActivity - android

I want to manage a list in a listView using onLongClick.
I want to select multiple items and manage (when is selected) adding in the toolbar 1 botton (remove).
I try with this code:
public class FragmentFragment extends Fragment {
private ListView listView;
private List<Schede> list;
private SchedeAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
}
});
listView = (ListView) rootView.findViewById(R.id.listView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object object= list.get(position);
Toast.makeText(getContext(), object.getName() + "Clicked", Toast.LENGTH_SHORT).show();
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
Object object = list.get(position);
view.setSelected(true);
return false;
}
});
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
return rootView;
}
public void remove(int position){
SharedPreferences pref = getActivity().getSharedPreferences("OBJECTS", Context.MODE_PRIVATE);
list.remove(position);
String listS = new Gson().toJson(list);
SharedPreferences.Editor edit = pref.edit();
edit.putString("OBJECTS", listS);
edit.apply();
adapter.notifyDataSetChanged();
}
public void refresh(){
SharedPreferences pref = getActivity().getSharedPreferences("OBJECTS", Context.MODE_PRIVATE);
String string = pref.getString("OBJECTS", null);
if (string != null){
Type type = new TypeToken<List<Object>>(){}.getType();
list = new Gson().fromJson(string, type);
adapter = new ObjectAdapter(getContext(), list);
listView.setAdapter(adapter);
}
}
#Override
public void onResume(){
super.onResume();
refresh();
}
}
...but don't allow me to select multiple items (I set different background color for selected items in xml).
The rest of code work correctly
Edit: post an example

Resolved: https://stackoverflow.com/a/12598337/6941150
Using in onCreate()...
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
...
}

Related

How to set an adapter to custom spinner in a list?

I have a ListFragment's list that contains complex layouts as items, these items contain custom spinners (MaterialSpinner).
MaterialSpinner chooseSubjectSpinner = adapter.getItem(position).findViewById(R.id.myCustomSpinner);
chooseSubjectSpinner.setAdapter(spinnerAdapter);
I've tried getChildAt(position), adapter.getItem(postition), adapter.getView(position, null, parent), and list.get(position) with the added prefix of .findViewById(R.id.myview), but it doesn't work. (It either returns NullPointerException at runtime or doesn't do anything at all!).
EDIT:
if you guys want the whole fragment code:
private ArrayList<View> listViews = new ArrayList<>();
private ViewAdapter adapter;
private List<String> spinnerItems = new ArrayList<>();
private MaterialSpinnerAdapter<String> spinnerAdapter;
public FragmentUnitTest() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_unit_test, container, false);
}
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState){
spinnerItems.add("Hey!");
spinnerItems.add("Hello!");
spinnerItems.add("Hi!");
spinnerAdapter = new MaterialSpinnerAdapter<>(getContext(), spinnerItems);
adapter = new ViewAdapter(listViews, view.getContext());
setListAdapter(adapter);
addView(R.layout.cardview_with_spinner);
MaterialSpinner spinner = adapter.getItem(0).findViewById(R.id.custom_spinner);
RLogger.e("FragmentUnitTest", spinner);
spinner.setAdapter(spinnerAdapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "Clicked: " + position + " .", Toast.LENGTH_SHORT).show();
}
Create a Custom spinner like this:
public class PTCustomSpinner extends ArrayAdapter {
public PTCustomSpinner(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
int count = super.getCount();
return count>0 ? count-1 : count ;
}
Handle it like below // BELOW XML LAYOUT CONTAINS ONLY TEXTVIEW WITH ID "temp"
PTCustomSpinner spinnerArrayAdapter = new PTCustomSpinner(PTExceptionMainPage.this, R.layout.xml_with_only_textview);
spinnerArrayAdapter.addAll(team_array);
spinnerArrayAdapter.add("Pick Team");
spinnerTeam.setAdapter(spinnerArrayAdapter);
spinnerTeam.setSelection(spinnerArrayAdapter.getCount());
spinnerTeam.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (spinnerTeam.getSelectedItem() != "Pick Team") {
teamIdSelected = apiResponseTeam.get(i).getTeamID();
}
else if( spinnerTeam.getSelectedItem().equals("Pick Team"))
{
View v = spinnerTeam.getSelectedView();
((TextView) v).setTextColor(getResources().getColor(R.color.ash));
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});

Android. OnItemSelectedListener doesn't work when spinner item selected

I have a Fragment where I dynamically create spinners. When I select item from spinner the onItemSelected doesn't trigger. Can I use AdapterView.OnItemSelectedListener interface in my approach? What am I doing wrong? Is there a best practices of handling item selection?
Here is the code:
public class ArticleAddParamsFragment extends Fragment implements AdapterView.OnItemSelectedListener {
private LinearLayout addPrLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_article_addparams, container, false);
addPrLayout = (LinearLayout) rootView.findViewById(R.id.addparams_layout);
setUpSpinners(getArguments().getLong("idArt"));
return rootView;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// doesn't go here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// doesn't go here
}
private void setUpSpinners(long idArt){
RealmAddParam addParForArt = realm.where(RealmAddParam.class)
.findAll()
.where()
.equalTo("idTaskart", idArt)
.findFirst();
for (RealmAddPrmMain prm: addParForArt.getAddParams()) {
addPrLayout.addView(createSpinner(prm));
}
}
public Spinner createSpinner(RealmAddPrmMain adPrm) {
Spinner spinner = new Spinner(getActivity());
spinner.setPrompt(adPrm.getNameAdd());
spinner.setFocusableInTouchMode(true);
spinner.setFocusable(true);
final ArrayList<SpinnerAdPrObj> spObjects = new ArrayList<>();
if (adPrm.getVvalue() != null) {
String[] values = adPrm.getVvalue().replace("[","").replace("]","").split(",");
if (values.length > 1){
for (Integer i = 0; i < values.length; i++){;
if (values[i].split(":::").length > 1) {
spObjects.add(new SpinnerAdPrObj(values[i].split(":::")[0], values[i].split(":::")[2], values[i].split(":::")[1]));
} else {
spObjects.add(new SpinnerAdPrObj(values[i].split(":::")[0]));
}
}
}
}
ArrayAdapter<SpinnerAdPrObj> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, spObjects);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
return spinner;
}
}
SOLUTION WAS:
just to add spinner.setOnItemSelectedListener(this);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});

I am having custom ListView having two textviews and one button i want to launch another activity on every button click in row?

i want when button is clicked in a row it will launch another activity which will show the detail of specific row.!
How to set Listener on button for each row.
Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] friendList = {"Javad","Usama","Umar","Bilal","Bhutta sb","Zain Ul Abidin"};
ListAdapter listAdapter = new CustomClass(this,friendList);
ListView listView = (ListView)findViewById(R.id.listview);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
String name = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(MainActivity.this,name,Toast.LENGTH_SHORT).show();
}
});
}
}
Inside onItemClick
if(view=R.id.ButtonID)
{
launch new Activity
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] friendList = {"Javad","Usama","Umar","Bilal","Bhutta sb","Zain Ul Abidin"};
ListAdapter listAdapter = new CustomClass(this,friendList);
ListView listView = (ListView)findViewById(R.id.listview);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
String name = String.valueOf(parent.getItemAtPosition(position));
Intent i = new Intent(this,SecondActivity.class);
i.putExtra("selectedValue",friendList[position]);
startActivity(i);
Toast.makeText(MainActivity.this,name,Toast.LENGTH_SHORT).show();
}
});
in second activity under OnCreate
if(getIntent().getExtras() != null)
{
String strData = getIntent().getExtras().getString("selectedValue")
}
you can bind button click listener in adapter not in onItemClick
before return view in a getView method.If you don't understand this answer then put your custom adapter code
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater myCustomInflater = LayoutInflater.from(getContext());
View customView = myCustomInflater.inflate(row, parent, false);
String singleFoodItem = getItem(position);
TextView itemText = (TextView) customView.findViewById(R.id.textView);
ImageView buckysImage = (ImageView) customView.findViewById(R.id.imageView);
itemText.setText(singleFoodItem);
Button button = customView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position == 0){
//go for next activity
}
}
});
itemText.setText(singleFoodItem);
buckysImage.setImageResource(R.mipmap.doctorcartoon);
return customView;
}

How to refresh ListView custom adapter data from the event listener that is in the adapter in Android?

I am a beginner to Android. Now I am working with ListView using custom adapter and custom view. Custom adapter is created as into a separate file. But inside my custom adapter, I set up a click listener for a button of the layout of the list view row. But my problem is how can I update items of the adapter inside event listener that is created inside the custom adapter.
This is my Listview Fragment:
public class TaskListFragment extends Fragment {
private DatabaseHelper dbHelper;
private TextView taskTitle;
private ListView taskListView;
private ArrayAdapter adapter;
private ArrayList<Task> items;
private int optionFocusedItemIndex;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
dbHelper = new DatabaseHelper(getActivity());
View view= inflater.inflate(R.layout.task_list, container, false);
taskTitle = (TextView)view.findViewById(R.id.task_textview);
taskListView = (ListView)view.findViewById(R.id.listViewTaskList);
int type = getArguments().getInt("type");
switch (type){
case R.integer.task_list_all:
items = dbHelper.getAllTasks();
adapter = new TaskListAdapter(getActivity(),items);
taskListView.setAdapter(adapter);
taskTitle.setText("All tasks");
break;
}
taskListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int tagId = Integer.valueOf(view.getTag().toString());
optionFocusedItemIndex = position;
showOptionDialog(tagId);
return true;
}
});
return view;
}
public void showOptionDialog(final int id)
{
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.row_option_dialog, null);
final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
Button doneBtn = (Button)view.findViewById(R.id.btn_row_option_done);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(id);
refreshListView();
alertDialog.cancel();
Toast.makeText(getActivity().getBaseContext(),"Marked as done",Toast.LENGTH_SHORT).show();
}
});
Button editBtn = (Button)view.findViewById(R.id.btn_row_option_edit);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity activity = (MainActivity)getActivity();
activity.replaceEditTaskFragment(id);
alertDialog.cancel();
}
});
Button deleteBtn = (Button)view.findViewById(R.id.btn_row_option_delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.deleteTask(id);
items.remove(optionFocusedItemIndex);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity().getBaseContext(),"Task deleted",Toast.LENGTH_SHORT).show();
alertDialog.cancel();
}
});
Button cancelBtn = (Button)view.findViewById(R.id.btn_row_option_cancel);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.cancel();
}
});
alertDialog.setView(view);
alertDialog.show();
}
public void refreshListView()
{
if(items!=null)
{
Task taskOld = items.get(optionFocusedItemIndex);
if(taskOld!=null)
{
taskOld.setDone(true);
items.set(optionFocusedItemIndex, taskOld);
adapter.notifyDataSetChanged();
}
}
}
}
Inside the fragment, when I click the done button listView adapter is updated properly and it is working find. Done button is inside the AlertDialog box that appear when long click on one of the rows of list view.
The problem is here.
This is my custom adapter class:
public class TaskListAdapter extends ArrayAdapter<Task> {
private final Context context;
private final ArrayList<Task> values;
private final DatabaseHelper dbHelper;
public TaskListAdapter(Context context,ArrayList<Task> values)
{
super(context,-1,values);
this.context = context;
this.values = values;
this.dbHelper = new DatabaseHelper(context.getApplicationContext());
}
#Override
public View getView(final int position,View convertView,ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.task_list_row,parent, false);
rowView.setTag(values.get(position).getId());
TextView rowDescription = (TextView)rowView.findViewById(R.id.task_row_description);
rowDescription.setText(values.get(position).getDescription());
ImageView rowStatusIcon = (ImageView)rowView.findViewById(R.id.task_row_status_icon);
Long currentDateMillSec= System.currentTimeMillis();
Long dateMillSec = CommonHelper.convertStrDateToMilSec(values.get(position).getDate());//(date==null)?0:date.getTime();
if(values.get(position).getDone()==Boolean.TRUE)
{
rowStatusIcon.setImageResource(R.drawable.done_icon);
}
else if(dateMillSec>0 && dateMillSec<currentDateMillSec)
{
rowStatusIcon.setImageResource(R.drawable.failed_icon);
}
else{
rowStatusIcon.setImageResource(R.drawable.todo_icon);
}
TextView dateTf = (TextView)rowView.findViewById(R.id.task_row_date);
dateTf.setText(values.get(position).getDate());
Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(values.get(position).getId());
//How can I update the listview items here ?
}
});
return rowView;
}
}
So how can I update the listview items and listview from the click event listener of done button that is inside custom adapter class.
public class TaskListFragment extends Fragment implements TaskListAdapter.RefreshAdapter{//change
private DatabaseHelper dbHelper;
private TextView taskTitle;
private ListView taskListView;
private ArrayAdapter adapter;
private ArrayList<Task> items;
private int optionFocusedItemIndex;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
dbHelper = new DatabaseHelper(getActivity());
View view= inflater.inflate(R.layout.task_list, container, false);
taskTitle = (TextView)view.findViewById(R.id.task_textview);
taskListView = (ListView)view.findViewById(R.id.listViewTaskList);
int type = getArguments().getInt("type");
switch (type){
case R.integer.task_list_all:
items = dbHelper.getAllTasks();
adapter = new TaskListAdapter(getActivity(),items);
taskListView.setAdapter(adapter);
adapter.setRefreshAdapter(this);//change
taskTitle.setText("All tasks");
break;
}
taskListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int tagId = Integer.valueOf(view.getTag().toString());
optionFocusedItemIndex = position;
showOptionDialog(tagId);
return true;
}
});
return view;
}
public void showOptionDialog(final int id)
{
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.row_option_dialog, null);
final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
Button doneBtn = (Button)view.findViewById(R.id.btn_row_option_done);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(id);
refreshListView();
alertDialog.cancel();
Toast.makeText(getActivity().getBaseContext(),"Marked as done",Toast.LENGTH_SHORT).show();
}
});
Button editBtn = (Button)view.findViewById(R.id.btn_row_option_edit);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity activity = (MainActivity)getActivity();
activity.replaceEditTaskFragment(id);
alertDialog.cancel();
}
});
Button deleteBtn = (Button)view.findViewById(R.id.btn_row_option_delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.deleteTask(id);
items.remove(optionFocusedItemIndex);
adapter.notifyDataSetChanged();
Toast.makeText(getActivity().getBaseContext(),"Task deleted",Toast.LENGTH_SHORT).show();
alertDialog.cancel();
}
});
Button cancelBtn = (Button)view.findViewById(R.id.btn_row_option_cancel);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.cancel();
}
});
alertDialog.setView(view);
alertDialog.show();
}
public void refreshListView()
{
if(items!=null)
{
Task taskOld = items.get(optionFocusedItemIndex);
if(taskOld!=null)
{
taskOld.setDone(true);
items.set(optionFocusedItemIndex, taskOld);
adapter.notifyDataSetChanged();
}
}
}
//change
#Override
public void OnlickRefreshAdapter(){
//todo your code here
items = dbHelper.getAllTasks();
adapter = new TaskListAdapter(getActivity(),items);
taskListView.setAdapter(adapter);
}
}
adapter class
public class TaskListAdapter extends ArrayAdapter<Task> {
private final Context context;
private final ArrayList<Task> values;
private final DatabaseHelper dbHelper;
private RefreshAdapter refreshAdapter;
public TaskListAdapter(Context context,ArrayList<Task> values)
{
super(context,-1,values);
this.context = context;
this.values = values;
this.dbHelper = new DatabaseHelper(context.getApplicationContext());
}
public Interface RefreshAdapter{
public void OnlickRefreshAdapter();
}
public setRefreshAdapter(RefreshAdapter refresh){
refreshAdapter = refresh;
}
#Override
public View getView(final int position,View convertView,ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.task_list_row,parent, false);
rowView.setTag(values.get(position).getId());
TextView rowDescription = (TextView)rowView.findViewById(R.id.task_row_description);
rowDescription.setText(values.get(position).getDescription());
ImageView rowStatusIcon = (ImageView)rowView.findViewById(R.id.task_row_status_icon);
Long currentDateMillSec= System.currentTimeMillis();
Long dateMillSec = CommonHelper.convertStrDateToMilSec(values.get(position).getDate());//(date==null)?0:date.getTime();
if(values.get(position).getDone()==Boolean.TRUE)
{
rowStatusIcon.setImageResource(R.drawable.done_icon);
}
else if(dateMillSec>0 && dateMillSec<currentDateMillSec)
{
rowStatusIcon.setImageResource(R.drawable.failed_icon);
}
else{
rowStatusIcon.setImageResource(R.drawable.todo_icon);
}
TextView dateTf = (TextView)rowView.findViewById(R.id.task_row_date);
dateTf.setText(values.get(position).getDate());
Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(values.get(position).getId());
//How can I update the listview items here ?
}
});
return rowView;
}
}
I got the answer, actually it is too simple. What I need to do is just add this code inside the click listener of done button in the custom adapter.
This is the click listener of the doneBtn in custom adapter:
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbHelper.markAsDone(values.get(position).getId());
//How can I update the listview items here ?
if(values!=null)
{
Task oldTask = values.get(position);
oldTask.setDone(Boolean.TRUE);
values.set(position,oldTask);
notifyDataSetChanged();
}
}
});

Fragment ListView Inflation of new Row to Maintain onItemClick Selection

I have a ListView that is within a Fragment. In the onCreateView section I have set a onItemClickListener for the list, which highlights the selected item in the ListView. I have set two ImageButtons that navigate up and down the list. On selection a new Row is inflated that has its TextView's set to the content of the select item (for the purpose of retaining the highlighted selected state). However I am having difficulty adding that item back to the list. The app will not compile due to the line routines.add(selectedPos-1, str); it wants wants int location, Routine object. I believe the issue is with my construction of my SelectedAdapter class, but I have been unable to determine what to change/pass with regard to the Object.
IE:
public SelectedAdapter(Context context, int textViewResourceId,List objects) {
super(getActivity(), R.layout.listview_routines, routines); }
I would greatly appreciate any input as how to correct this issue; as well as any advice if there is a better way to maintain a selected state. Thanks for your help.
Fragment:
public static class FragmentRoutine extends Fragment {
DatabaseHandler db;
private ListView routineListView;
private List<Routine> routines = new ArrayList<Routine>();
ArrayAdapter<Routine> routineAdapter;
Routine longClickedItemRoutines;
private SelectedAdapter selectedAdapter;
public FragmentRoutine() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.routines,
container, false);
db = new DatabaseHandler(getActivity().getApplicationContext());
routineListView = (ListView) rootView.findViewById(R.id.routineList);
registerForContextMenu(routineListView);
db.closeDB();
if (db.getExerciseCount() != 0)
routines.clear();
routines.addAll(db.getAllRoutines());
populateList();
selectedAdapter = new SelectedAdapter(this.getActivity(), 0, routines);
selectedAdapter.setNotifyOnChange(true);
routineListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemRoutines = routines.get(position);
return false;
}
});
routineListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0, View view,
int position, long id) {
selectedAdapter.setSelectedPosition(position);
}
});
routineListView.post(new Runnable() {
#Override
public void run() {
routineListView.setItemChecked(0, true);
}
});
// move up event handler
ImageButton btnMoveUp = (ImageButton) rootView.findViewById(R.id.btnMoveUp);
btnMoveUp.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveUp();
}
});
// move down event handler
ImageButton btnMoveDown = (ImageButton) rootView.findViewById(R.id.btnMoveDown);
btnMoveDown.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveDown();
}
});
setHasOptionsMenu(true);
return rootView;
}
// Move selected item "up" in the ViewList.
private void moveUp(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos > 0 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
//Problem Line Below
routines.add(selectedPos-1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos-1);
}
}
// Move selected item "down" in the ViewList.
private void moveDown(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos < routines.size()-1 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
routines.add(selectedPos+1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos+1);
}
}
public class SelectedAdapter extends ArrayAdapter<Routine>{
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
public SelectedAdapter(Context context, int textViewResourceId,
List objects) {
super(getActivity(), R.layout.listview_routines, routines);
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// only inflate the view if it's null
if (v == null) {
LayoutInflater vi
= (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.selected_row, null);
}
// get text view
TextView label = (TextView)v.findViewById(R.id.txtExample);
// change the row color based on selected state
if(selectedPos == position){
label.setBackgroundColor(Color.CYAN);
}else{
label.setBackgroundColor(Color.WHITE);
}
label.setText(this.getItem(position).toString());
return(v);
}
}
private void populateList() {
routineAdapter = new SaveListAdapterT();
routineListView.setAdapter(routineAdapter);
}
public class SaveListAdapterT extends ArrayAdapter<Routine> {
public SaveListAdapterT() {
super(getActivity(), R.layout.listview_routines, routines);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.listview_routines, parent, false);
Routine currentToDoSave = routines.get(position);
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(currentToDoSave.getTagName());
return view;
}
}
}

Categories

Resources