I want to Show a Tabbed based inside Dialog so for this I use This Library.
I am able to populate my Dialog and also Tab is switching from Tab_1 to Tab_2. But when I am clicking on its Cancel, Ok or Neutral Button, I am not getting Toast.
Please guide me how can I use Initialize Fragments and Toast on Button Click in my BaseAdapter.
My code is here
public class ContactListAdapter extends BaseAdapter implements ISimpleDialogListener, ISimpleDialogCancelListener,IFragmentListener {
slidingListItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
contactListItems = contactList.get(position);
String id_attende = contactListItems.getPhone();
String id_attende_name = contactListItems.getName();
TabDialogFragment.createBuilder(context, mFragmentManager)
.setTitle(id_attende_name)
.setSubTitle(id_attende)
.setTabButtonText(new CharSequence[]{"Calendar", "Summary"})
.setPositiveButtonText("Ok")
.setNegativeButtonText("Cancel")
.setNeutralButtonText("Neutral")
.setRequestCode(REQUEST_TABBED_DIALOG)
.show();
}
});
return convertView;
}
#Override
public void onCancelled(int requestCode) {
switch (requestCode) {
case REQUEST_TABBED_DIALOG:
Toast.makeText(context, "Dialog cancelled", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
#Override
public void onNegativeButtonClicked(int requestCode) {
if (requestCode == REQUEST_TABBED_DIALOG) {
Toast.makeText(context, "Negative button clicked", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNeutralButtonClicked(int requestCode) {
if (requestCode == REQUEST_TABBED_DIALOG) {
Toast.makeText(context, "Neutral button clicked", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPositiveButtonClicked(int requestCode) {
if (requestCode == REQUEST_TABBED_DIALOG) {
Toast.makeText(context, "Positive button clicked", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFragmentViewCreated(Fragment fragment) {
int selectedTabPosition = fragment.getArguments().getInt(PageFragment.ARG_DAY_INDEX, 0);
View rootContainer = fragment.getView().findViewById(R.id.root_container);
Log.i(TAG, "Position: " + selectedTabPosition);
switch (selectedTabPosition) {
case 0:
selectedTabPositionZeroCase(rootContainer);
break;
case 1:
selectedTabPositionOneCase(rootContainer);
break;
default:
break;
}
}
private void selectedTabPositionZeroCase(View rootContainer) {
// add view in container for first tab
LayoutInflater li = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View tabProductDetailLayout = li.inflate(R.layout.tab_one_layout, (ViewGroup) rootContainer);
TextView textView = (TextView) tabProductDetailLayout.findViewById(R.id.text_view);
textView.setText("hello: tab1");
}
private void selectedTabPositionOneCase(View rootContainer) {
// add view in container for second tab
LayoutInflater li = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View tabProductDetailLayout2 = li.inflate(R.layout.tab_one_layout, (ViewGroup) rootContainer);
TextView textView1 = (TextView) tabProductDetailLayout2.findViewById(R.id.text_view);
textView1.setText("hello: tab2");
}
#Override
public void onFragmentAttached(Fragment fragment) {
mMyScheduleFragments.add(fragment);
}
#Override
public void onFragmentDetached(Fragment fragment) {
mMyScheduleFragments.remove(fragment);
}
}
Actually from the link, you have provided, They are passing the MainActivity.this where you are passing context and there is a problem. So as per my suggestion just implement these callbacks in your MainActivity.java class instead of Adapter class.
Related
I have a RecyclerView list that displays an item which houses some TextViews and Buttons. I have already linked the buttons of each item to a specific function. The fragment looks like this.
The two buttons (Red and Blue) changes its function based on the user's status. e.g. when a user is not approved, the blue button will show "Activate Account" and the red button will show "Remove Request", each with their own function. All the functions of the button work as intended, but there is a slight problem. When I click on one of the two buttons, it sometimes won't register the click. I think it might have to do with the RecyclerView's scrolling property. Is there any way to overcome this problem? I want those buttons to function as normal buttons that when the buttons are touched, it will always register as a button click, not a recyclerview drag.
RecyclerView Adapter:
class AccountViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView text_name;
TextView text_username;
TextView text_status1; // Approved | Pending
TextView text_status2; // Admin
TextView text_status3; // Operator
Button button_left; // Deactivate | Remove Request
Button button_right; // Admin | Activate
private WeakReference<AccountListClickListener> listenerRef;
public AccountViewHolder(#NonNull View itemView, AccountListClickListener clickListener) {
super(itemView);
listenerRef = new WeakReference<>(clickListener);
text_name = itemView.findViewById(R.id.acc_name);
text_username = itemView.findViewById(R.id.acc_username);
text_status1 = itemView.findViewById(R.id.acc_status);
text_status2 = itemView.findViewById(R.id.acc_status2);
text_status3 = itemView.findViewById(R.id.acc_status3);
button_left = itemView.findViewById(R.id.button_left);
button_right = itemView.findViewById(R.id.button_right);
button_left.setOnClickListener(this);
button_right.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId() == button_left.getId())
listenerRef.get().leftButtonClick(getAdapterPosition(), button_left.getText().toString(), text_username.getText().toString().substring(10));
if (view.getId() == button_right.getId())
listenerRef.get().rightButtonClick(getAdapterPosition(), button_right.getText().toString(), text_username.getText().toString().substring(10));
}
}
public void setFilter(int i){
this.statusFilter = i;
}
}
RecyclerView Fragment
public class AccountFragment extends Fragment implements RadioGroup.OnCheckedChangeListener {
private RecyclerView recyclerView;
private List<Account> accountList;
private AccountAdapter accountAdapter;
private Timer timer;
private View view;
private boolean isActive;
private RadioGroup rg1, rg2;
private int filter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
isActive = true;
return inflater.inflate(R.layout.fragment_account, container, false);
}
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.view = view;
accountList = new ArrayList<>();
rg1 = view.findViewById(R.id.fg_acc1);
rg2 = view.findViewById(R.id.fg_acc2);
rg1.setOnCheckedChangeListener(this);
rg2.setOnCheckedChangeListener(this);
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(isActive) {
((MainActivity) getActivity()).populateAccountCards();
}
}
});
}
}, 0, 100);
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("account");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snap : snapshot.getChildren()){
accountList.add(snap.getValue(Account.class));
}
accountAdapter = new AccountAdapter(view.getContext(), accountList, new AccountAdapter.AccountListClickListener() {
#Override
public void leftButtonClick(int i, String button, String username) {
switch(button){
case "DEACTIVATE ACCOUNT":
modifyAccount(ref, 0, username);
break;
case "REMOVE REQUEST":
modifyAccount(ref, 1, username);
break;
}
}
#Override
public void rightButtonClick(int i, String button, String username) {
switch(button){
case "REMOVE AS ADMIN":
modifyAccount(ref, 2, username);
break;
case "MAKE ADMIN":
modifyAccount(ref, 3, username);
break;
case "ACTIVATE ACCOUNT":
modifyAccount(ref, 4, username);
break;
}
}
});
recyclerView = view.findViewById(R.id.recyclerView2);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
recyclerView.setAdapter(accountAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public AccountAdapter getAccountAdapter(){
return this.accountAdapter;
}
/*
0 - Deactivate Account
1 - Remove Account
2 - Remove as Admin
3 - Make Admin
4 - Activate Account
*/
private void modifyAccount(DatabaseReference ref, final int i, final String user) {
final Fragment currentFragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_container);
final FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
DatabaseUtil.readDataByUsername(user, ref, new OnGetDataListener() {
#Override
public void dataRetrieved(final DataSnapshot dataSnapshot) {
switch(i){
case 0:
DialogInterface.OnClickListener dialogClickListener1 = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
dataSnapshot.getRef().child("activated").setValue(false);
dataSnapshot.getRef().child("admin").setValue(false);
fragmentTransaction.detach(currentFragment);
fragmentTransaction.attach(currentFragment);
fragmentTransaction.commit();
break;
case DialogInterface.BUTTON_NEGATIVE:
Toast.makeText(getContext(), "Action Cancelled", Toast.LENGTH_LONG).show();
break;
}
}
};
AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
builder1.setMessage("Deactivate Account of " + user + "?").setPositiveButton("Yes", dialogClickListener1)
.setNegativeButton("No", dialogClickListener1).show();
break;
case 1:
DialogInterface.OnClickListener dialogClickListener2 = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
dataSnapshot.getRef().removeValue();
fragmentTransaction.detach(currentFragment);
fragmentTransaction.attach(currentFragment);
fragmentTransaction.commit();
break;
case DialogInterface.BUTTON_NEGATIVE:
Toast.makeText(getContext(), "Action Cancelled", Toast.LENGTH_LONG).show();
break;
}
}
};
AlertDialog.Builder builder2 = new AlertDialog.Builder(getContext());
builder2.setMessage("Delete Account of " + user + "?\nWARNING: ALL DATA WILL BE LOST").setPositiveButton("Yes", dialogClickListener2)
.setNegativeButton("No", dialogClickListener2).show();
break;
case 2:
DialogInterface.OnClickListener dialogClickListener3 = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
dataSnapshot.getRef().child("admin").setValue(false);
fragmentTransaction.detach(currentFragment);
fragmentTransaction.attach(currentFragment);
fragmentTransaction.commit();
break;
case DialogInterface.BUTTON_NEGATIVE:
Toast.makeText(getContext(), "Action Cancelled", Toast.LENGTH_LONG).show();
break;
}
}
};
AlertDialog.Builder builder3 = new AlertDialog.Builder(getContext());
builder3.setMessage("Remove Admin Access of " + user + "?").setPositiveButton("Yes", dialogClickListener3)
.setNegativeButton("No", dialogClickListener3).show();
break;
case 3:
DialogInterface.OnClickListener dialogClickListener4 = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
dataSnapshot.getRef().child("admin").setValue(true);
fragmentTransaction.detach(currentFragment);
fragmentTransaction.attach(currentFragment);
fragmentTransaction.commit();
break;
case DialogInterface.BUTTON_NEGATIVE:
Toast.makeText(getContext(), "Action Cancelled", Toast.LENGTH_LONG).show();
break;
}
}
};
AlertDialog.Builder builder4 = new AlertDialog.Builder(getContext());
builder4.setMessage("Grant Admin Access to " + user + "?").setPositiveButton("Yes", dialogClickListener4)
.setNegativeButton("No", dialogClickListener4).show();
break;
case 4:
DialogInterface.OnClickListener dialogClickListener5 = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
dataSnapshot.getRef().child("activated").setValue(true);
fragmentTransaction.detach(currentFragment);
fragmentTransaction.attach(currentFragment);
fragmentTransaction.commit();
break;
case DialogInterface.BUTTON_NEGATIVE:
Toast.makeText(getContext(), "Action Cancelled", Toast.LENGTH_LONG).show();
break;
}
}
};
AlertDialog.Builder builder5 = new AlertDialog.Builder(getContext());
builder5.setMessage("Activate Account of " + user + "?").setPositiveButton("Yes", dialogClickListener5)
.setNegativeButton("No", dialogClickListener5).show();
break;
}
}
#Override
public void dataExists(DataSnapshot dataSnapshot) {
}
#Override
public void onStart() {
}
#Override
public void onFailure() {
}
});
}
I solved it! Apparently I have a timer thread that runs at a fixed interval which calls a function to populate the cards and filter the items based on the radiobutton filter selected. The timer executes that function every 100 milliseconds that updates the item adapter, which doesn't give the system enough time to register the button press. Changing the timer interval to a longer duration solved the problem.
It made sense as when I touch the button for more than 100 milliseconds, the system wouldn't recognize that I touched the original button anymore because it already populated a new set of viewholders and ultimately, the button I was touching was now gone, along with its onclick function.
My app uses a firebase RecyclerAdapter to display "plant" entities in an activity.
I made it so that if I longclick on an entity displayed in Cardview format using a ViewHolder and the RecyclerAdapter it will prompt to perform a delete and delete the plant entity + image on the firebase database and storage. Deleting and adding plants work without a hitch on the backend as I can confirm this on my firebase database.
However, when I delete a "plant" entity and add a new one, the CardView shows the previous or another image. Deleting the app and reinstalling it seems to fix the problem, because of this I think it might have to do with the local cache.
PlantActivity.java (where the plants are loaded)
I think this might be solved if there was some way to refresh the activity in some way or the RecyclerAdapter... although i've tried many things already
public class PlantActivity extends AppCompatActivity {
private static final int ADD_REQUEST = 101;
private static final String TAG = "PlantActivityView";
private DatabaseReference mDatabaseReference;
private FirebaseRecyclerAdapter plantAdapter;
private PlantDAO mPlantDAO;
private UserDAO mUserDAO;
private CoordinatorLayout coordinatorLayout;
#Override
protected void onStart() {
super.onStart();
if(!mUserDAO.isLoggedIn()){
finish();
startActivity(new Intent(PlantActivity.this, LoginActivity.class));
}
plantAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
plantAdapter.stopListening();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plant_view);
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mPlantDAO = new PlantDAO(mDatabaseReference);
mUserDAO = new UserDAO();
//make custom appcompat toolbar to replace actionbar and add logout item
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
coordinatorLayout = findViewById(R.id.plant_coordinator);
providePlantsOfCurrentUser();
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),PlantAddActivity.class);
startActivityForResult(intent, ADD_REQUEST);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menuLogout:
mUserDAO.getAuth().signOut();
finish();
startActivity(new Intent(PlantActivity.this,LoginActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Snackbar GoodResultSnackbar = Snackbar.make(coordinatorLayout,"PLANT ADDED",Snackbar.LENGTH_SHORT);
Snackbar BadResultSnackbar = Snackbar.make(coordinatorLayout,"PLANT ADD FAILED",Snackbar.LENGTH_SHORT);
if(requestCode == ADD_REQUEST){
if(resultCode == Activity.RESULT_OK){
GoodResultSnackbar.show();
} else if(resultCode == Activity.RESULT_CANCELED){
BadResultSnackbar.show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void providePlantsOfCurrentUser(){
FirebaseRecyclerOptions<Plant> options = new FirebaseRecyclerOptions.Builder<Plant>().setQuery(mPlantDAO.currentUserPlantsQuery(), Plant.class).build();
plantAdapter = new FirebaseRecyclerAdapter<Plant,PlantViewHolder>(options) {
#NonNull
#Override
public PlantViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview_item_plant, parent, false);
return new PlantViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull final PlantViewHolder holder, final int position, #NonNull final Plant model) {
StorageReference localstorage = FirebaseStorage.getInstance().getReferenceFromUrl(model.getImageLocation());
String plantText = /*model.getPlantID() + ": " + */ model.getPlanttype();
holder.tv_plant_name.setText(plantText);
//image implementation
GlideApp.with(getApplicationContext()).load(localstorage).into(holder.img_plant_thumbnail);
holder.dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
mPlantDAO.deletePlant(model.getPlantID());
plantAdapter.notifyDataSetChanged();
break;
case DialogInterface.BUTTON_NEGATIVE:
//Return
break;
}
}
};
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//passing data with intent to PlantDetailActivity instance
Intent intent = new Intent(getApplicationContext(), PlantDetailActivity.class);
intent.putExtra("plantID", model.getPlantID());
intent.putExtra("planttype", model.getPlanttype());
//image implementation
intent.putExtra("image_url", model.getImageLocation());
//start the activity
startActivity(intent);
}
});
holder.cardView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showDeleteDialog(holder);
return true;
}
});
}
};
RecyclerView recyclerView = findViewById(R.id.recyclerview_id);
recyclerView.setAdapter(plantAdapter);
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
}
private void showDeleteDialog(PlantViewHolder holder){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete this plant?").setPositiveButton("Yes", holder.dialogClickListener)
.setNegativeButton("Cancel", holder.dialogClickListener).show();
}
}
The position and model are final on the onBindViewHolder method
The viewholder can be final, but not the data or the position
Use holder.getAdapterPosition() to get the position inside annonymous interfaces like click listeners
And then get the data using getItem() method from the adapter class
The last answer by #cutiko definitely helped! But I think I realize the problem. I was saving my plantID string attribute (of new Plant object) in this fashion:
"plant_" + count() of "plants" in database + "_" + ID of the current user + ".jpg"
The problem this causes is that when I delete a plant entity and add another this could cause 2 plant entities in the database to have the same ID which causes strange behavior.
I will solve this by instead of deleting a plant from the database, changing a new attribute's("active") to false and not showing these in the FirebaseRecyclerAdapter
I am developing an android application, in that i using displaying pull notifications. I am getting the list of notification from backend and displaying in the form of custom list view.The problem is i am providing a button to delete particular notification from list view when ever i tried to delete the notification at any index it is deleting but after scrolling the entire list view is getting refreshed. How can i handle this?
one more thing is i am not using notifysetdatachange() anywhere.
public class NotificationListViewHolder extends BaseListAdapter.ViewHolder {
//timeStamp, userName;
public final CircleImageView profilePicture;
public final TextView timeStamp;
public final ImageView deleteNotification;
public final ProgressBar progressBar;
public final RelativeLayout notificationListItem;
public TextView requirement;
public LinearLayout clickableArea;
NotificationListViewHolder viewHolder;
NotificationListAdapter listAdapter;
public NotificationListViewHolder(View view, BaseListAdapterListener listener, NotificationListAdapter listAdapter) {
super(view, listener);
requirement = view.findViewById(R.id.requirement);
profilePicture = view.findViewById(R.id.profile_picture);
notificationListItem = view.findViewById(R.id.notification_list_item);
deleteNotification = view.findViewById(R.id.delete_notification);
progressBar = view.findViewById(R.id.progressBar);
clickableArea = view.findViewById(R.id.clickable_area);
timeStamp = view.findViewById(R.id.time_stamp);
this.listAdapter = listAdapter;
}
public void bind(final Notification entry, NotificationListViewHolder holder) {
try {
if (holder.notificationListItem.getTag() == null) {
holder.notificationListItem.setTag(holder);
} else {
viewHolder = (NotificationListViewHolder) holder.notificationListItem.getTag();
}
viewHolder.progressBar.setVisibility(entry.isSelected()
? View.VISIBLE : View.GONE);
viewHolder.deleteNotification.setVisibility(entry.isSelected()
? View.GONE : View.VISIBLE);
viewHolder.requirement.setText(entry.getRequirement());
if (entry.getRoleName().equals("")) {
viewHolder.timeStamp.setText(TimeFormat.getTimeStamp(entry.getTimestamp(), TimeFormatTypes.FORMAT_DESCRIPTION) + "");
} else {
viewHolder.timeStamp.setText(entry.getRoleName() + " - " + TimeFormat.getTimeStamp(entry.getTimestamp(), TimeFormatTypes.FORMAT_DESCRIPTION) + "");
}
if (viewHolder.profilePicture != null && !entry.getProfileUrl().equalsIgnoreCase("")) {
Picasso.with(D4E.getContext()).load(D4E.getContext().getResources().getString(R.string.liferay_server) + entry.getProfileUrl()).placeholder(R.drawable.default_profile_pic)
.error(R.drawable.default_profile_pic).into(viewHolder.profilePicture);
}
if (entry.getType() == 1) { // light grey , my post notifications || other post notification
viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#C8FAD2"));
viewHolder.requirement.setTextColor(Color.parseColor("#030303"));
} else if (entry.getType() == 2) {
// the posts by others
/* viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#DCDCDC"));
viewHolder.requirement.setTextColor(Color.parseColor("#030303"));*/
} else if (entry.getType() == 0) { // dark grey , admin
viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#FAFAC8"));
viewHolder.requirement.setTextColor(Color.parseColor("#030303"));
}
viewHolder.clickableArea.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
entry.setSelected(true);
deleteNotification();
viewHolder.progressBar.setVisibility(View.VISIBLE);
viewHolder.deleteNotification.setVisibility(View.GONE);
}
private void deleteNotification() {
Session session = SessionContext.createSessionFromCurrentSession();
session.setCallback(new Callback() {
#Override
public void inBackground(Response response) {
((Activity) D4E.getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
try {
viewHolder.progressBar.setVisibility(View.GONE);
AnimatorUtil.animate(viewHolder/*, true*/);
listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getLayoutPosition()));
listAdapter.notifyItemRemoved(viewHolder.getLayoutPosition());
UserInfoController.initializeUserInfoController().getUserInfo().setNotificationCount(listAdapter.getEntries().size());
/* listAdapter.notifyDataSetChanged();
listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getLayoutPosition()));
listAdapter.notifyItemRemoved(viewHolder.getLayoutPosition());
listAdapter.notifyItemRangeChanged(viewHolder.getLayoutPosition(), listAdapter.getEntries().size());
listAdapter.notifyDataSetChanged();
UserInfoController.initializeUserInfoController().getUserInfo().setNotificationCount(listAdapter.getEntries().size());*/
/*if (listAdapter.getEntries().size() == 0)
(() D4E.getContext()).onNoListItem();*/
} catch (Exception e) {
Log.e("Ex:Noti_List_Adp", "" + e.toString());
}
}
});
}
#Override
public void doFailure(Exception exception) {
viewHolder.progressBar.setVisibility(View.GONE);
viewHolder.deleteNotification.setVisibility(View.VISIBLE);
entry.setSelected(false);
}
});
try {
new DeccategoryService(session).DeleteNotification(Long.parseLong(entry.getNotificationId()));
} catch (Exception e) {
e.printStackTrace();
}
}
});
/* if (holder.notificationListItem.getTag() == null) {
holder.notificationListItem.setTag(holder);
} else {
viewHolder = (NotificationListViewHolder) holder.notificationListItem.getTag();
}*/
/* viewHolder.clickableArea.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
entry.setSelected(true);
// adapter.removeItem(entry,getAdapterPosition());
openDeleteNotification();
viewHolder.progressBar.setVisibility(View.VISIBLE);
viewHolder.deleteNotification.setVisibility(View.GONE);
}
private void openDeleteNotification() {
Session session = SessionContext.createSessionFromCurrentSession();
session.setCallback(new Callback() {
#Override
public void inBackground(Response response) {
((Activity) D4E.getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
viewHolder.progressBar.setVisibility(View.GONE);
adapter.removeItem(entry, getAdapterPosition());
}
});
}
#Override
public void doFailure(Exception exception) {
viewHolder.progressBar.setVisibility(View.GONE);
viewHolder.deleteNotification.setVisibility(View.VISIBLE);
entry.setSelected(false);
}
});
try {
new DeccategoryService(session).DeleteNotification(Long.parseLong(entry.getNotificationId()));
} catch (Exception e) {
e.printStackTrace();
}
}
});*/
viewHolder.progressBar.setVisibility(entry.isSelected()
? View.VISIBLE : View.GONE);
viewHolder.deleteNotification.setVisibility(entry.isSelected()
? View.GONE : View.VISIBLE);
viewHolder.requirement.setText(entry.getRequirement());
if (entry.getRoleName().equals("")) {
viewHolder.timeStamp.setText(TimeFormat.getTimeStamp(entry.getTimestamp(), TimeFormatTypes.FORMAT_DESCRIPTION) + "");
} else {
viewHolder.timeStamp.setText(entry.getRoleName() + " - " + TimeFormat.getTimeStamp(entry.getTimestamp(), TimeFormatTypes.FORMAT_DESCRIPTION) + "");
}
if (viewHolder.profilePicture != null && !entry.getProfileUrl().equalsIgnoreCase("")) {
Picasso.with(D4E.getContext()).load(D4E.getContext().getResources().getString(R.string.liferay_server) + entry.getProfileUrl()).placeholder(R.drawable.default_profile_pic)
.error(R.drawable.default_profile_pic).into(viewHolder.profilePicture);
}
if (entry.getType() == 1) {
viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#F2F2F2"));
viewHolder.requirement.setTextColor(Color.parseColor("#030303"));
} else if (entry.getType() == 2) {
/* viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#DCDCDC"));
viewHolder.requirement.setTextColor(Color.parseColor("#030303"));*/
} else {
viewHolder.notificationListItem.setBackgroundColor(Color.parseColor("#FFFFFF"));//admin post color
}
// FontStyle.getInstance().FontStyleByGroupOfIds(view.getContext(), new int[]{R.id.notification_list_item}, view);
} catch (Exception e) {
Log.e("Exception", e.toString());
}
}
public void createDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(D4E.getContext());
builder.setTitle("Alert!");
builder.setMessage("Message from Admin");
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
}
}
public class Notifications extends Scheduler implements ScreenletListListener, SearchView.OnQueryTextListener, NoListListener, UpdateLogout {
public static boolean isInSettingsPage;
public static long notificationId;
public static String notificationSearchKeyword = "";
public static boolean notificationSearchActivated = false;
public static boolean navigatedFromPush = false;
ArrayList<digital.engineers.club.models.Notifications> notificationsModel;
BottomSheetDialog dialog;
View dialogView;
Menu menu;
GenericScreenlet screenlet;
SearchView searchView;
MenuItem searchMenuItem;
LinearLayout container;
View screenletView, noIntimationView;
private boolean shudRefreshOnResume = false;
//Push test
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notifications);
setContext(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
container = findViewById(R.id.ns);
D4E.setContext(this);
FontStyle.getInstance().setContext(this);
getSupportActionBar().setTitle(FontStyle.getInstance()
.getSpannableString(getSupportActionBar().getTitle().toString()));
container = findViewById(R.id.container);
noIntimationView = View.inflate(this, R.layout.no_list_intimation, null);
refreshNotifications();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.notification_menu, menu);
this.menu = menu;
final MenuItem menuItem = menu.findItem(R.id.nsettings);
BitmapDrawable icon = (BitmapDrawable) menuItem.getIcon();
Drawable drawable = DrawableCompat.wrap(icon);
DrawableCompat.setTint(drawable, getResources().getColor(R.color.white));
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchMenuItem = menu.findItem(R.id.search);
searchView = (SearchView) searchMenuItem.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(this);
searchView.setSubmitButtonEnabled(false);
searchView.setIconifiedByDefault(true);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (isInSettingsPage) {
resetNotificationPage();
isInSettingsPage = false;
} else {
if (navigatedFromPush) {
startActivity(new Intent(this, HomeScreen.class));
navigatedFromPush = false;
} else
finish();
}
} else if (item.getItemId() == R.id.search) {
} else if (item.getItemId() == R.id.nsettings) {
isInSettingsPage = true;
loadSettings();
}
return super.onOptionsItemSelected(item);
}
public void loadSettings() {
FontStyle.getInstance().setContext(this);
getSupportActionBar().setTitle(FontStyle.getInstance().getSpannableString("Notification Settings"));
container.removeAllViews();
if (searchMenuItem.isActionViewExpanded())
searchMenuItem.collapseActionView();
menu.getItem(0).setVisible(false);
menu.getItem(1).setVisible(false);
getFragmentManager().beginTransaction().replace(R.id.container, new NotificationSettingsFragment()).commit();
}
private void openbootomsheet() {
dialog = new BottomSheetDialog(Notifications.this);
dialogView = View.inflate(Notifications.this, R.layout.search_posts, null);
dialogView.findViewById(R.id.search_by_time_layout);
dialog.setContentView(dialogView);
((Spinner) dialogView.findViewById(R.id.posted_time)).setAdapter(new ArrayAdapter<String>(Notifications.this, android.R.layout.simple_list_item_1,
android.R.id.text1,
getResources().getStringArray(R.array.day_search)));
((Spinner) dialogView.findViewById(R.id.role)).setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
android.R.id.text1,
getResources().getStringArray(R.array.roles)));
dialog.show();
dialogView.findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialogView.findViewById(R.id.search_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
#Override
public void onListPageReceived(int startRow, int endRow, List<Object> entries, int rowCount) {
// Toast.makeText(this,"Success",Toast.LENGTH_LONG).show();
//UserInfoController.initializeUserInfoController().getUserInfo().setNotificationCount(0);
UserInfoController.initializeUserInfoController().getUserInfo().setNotificationCount(entries.size());
if (entries.size() == 0) {
showNoNotificationIntimation();
}
/*screenlet.setVisibility(entries.size() > 0 ? View.VISIBLE : View.GONE);
((LinearLayout) findViewById(R.id.no_list_layout)).setVisibility(entries.size() > 0 ? View.GONE : View.VISIBLE);*/
}
#Override
public void onListItemSelected(Object element, View view) {
Notification notification = (Notification) element;
if (notification != null) {
if (((Notification) element).getType() != 0) {
notificationId = Long.parseLong(notification.getNotificationId());
NewPost.postType = (SessionContext.getUserId() == Long.parseLong(notification.getPostedUserId())) ?
getResources().getString(R.string.post_type_my_post) :
getResources().getString(R.string.post_type_relevant_post);
Map<String, Object> postMap = new HashMap<>();
postMap.put("threadId", notification.getThreadId());
postMap.put("profileUrl", SessionContext.getUserId() == Long.parseLong(notification.getPostedUserId()) ?
UserInfoController.initializeUserInfoController().getUserInfo().getProfileUrl() :
notification.getProfileUrl());
postMap.put("firstName", notification.getFirstName());
postMap.put("lastName", notification.getLastName());
postMap.put("categoryId", notification.getCategoryId());
postMap.put("timestamp", notification.getTimestamp());
postMap.put("subject", notification.getSubject());
postMap.put("threadStatus", notification.getThreadStatus());
postMap.put("userId", String.valueOf(SessionContext.getUserId()));
postMap.put("postedUserId", notification.getPostedUserId());
postMap.put("userName", notification.getUserName());
postMap.put("roleName", notification.getRoleName());
// postMap.put("attachment",notification.getAttachment());
ViewThread.post = new Post(postMap);
ViewThread.post.setAttachment(notification.getAttachment());
NewPost.currentPostId = ViewThread.post.getThreadId();
NewPost.currentPosition = (SessionContext.getUserId() == Long.parseLong(notification.getPostedUserId())) ?
0 : 1; // View Pager position
NewPost.postedUserId = Long.parseLong(ViewThread.post.getPostedUserId());
HomeScreen.categoryId = Long.parseLong(ViewThread.post.getCategoryId());
Intent intent = new Intent(Notifications.this, ViewThread.class);
intent.putExtra("THREAD", ViewThread.post);
startActivity(intent);
} else {
createDialog(notification.getRequirement());
}
}
}
#Override
public void error(Exception e, String userAction) {
// Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void onListPageFailed(int startRow, Exception e) {
// Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void interactorCalled() {
}
#Override
protected void onResume() {
super.onResume();
if (isScreenOn(this) && hasTimedOut) {
initializeTimer();
resetTimeOut();
startSessionTimeCountDown();
}
if (shudRefreshOnResume) {
if (!isInSettingsPage) {
refreshNotifications();
shudRefreshOnResume = false;
} else {
loadSettings();
}
}
}
#Override
protected void onPause() {
super.onPause();
shudRefreshOnResume = true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() > 3) {
notificationSearchKeyword = newText;
notificationSearchActivated = true;
refreshNotifications();
} else if (newText.length() == 0) {
notificationSearchKeyword = "";
notificationSearchActivated = false;
refreshNotifications();
}
return true;
}
public void refreshNotifications() {
container.removeAllViews();
View notificationScreenlet = View.inflate(this, R.layout.notification_list_screenlet, null);
screenlet = notificationScreenlet.findViewById(R.id.notification_list_screenlet);
screenlet.setPagination();
screenlet.setListener(this);
container.addView(notificationScreenlet);
}
public void resetNotificationPage() {
FontStyle.getInstance().setContext(this);
getSupportActionBar().setTitle(FontStyle.getInstance().getSpannableString("Notifications"));
menu.getItem(0).setVisible(true);
menu.getItem(1).setVisible(true);
refreshNotifications();
notificationSearchActivated = false;
}
private void setItemsVisibility(Menu menu, MenuItem exception, boolean visible) {
for (int i = 0; i < menu.size(); ++i) {
MenuItem item = menu.getItem(i);
if (item != exception) item.setVisible(visible);
}
}
#Override
public void onBackPressed() {
notificationSearchActivated = false;
if (isInSettingsPage) {
resetNotificationPage();
isInSettingsPage = false;
} else {
if (navigatedFromPush) {
startActivity(new Intent(this, HomeScreen.class));
navigatedFromPush = false;
} else
finish();
}
}
public void createDialog(String message) {
final AlertDialog.Builder builder = new AlertDialog.Builder(D4E.getContext());
builder.setTitle("Message from Admin");
builder.setMessage(message);
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
}
public void showNoNotificationIntimation() {
container.removeAllViews();
noIntimationView.findViewById(R.id.no_list_layout).setLayoutParams(new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
container.addView(noIntimationView);
}
#Override
public void onNoListItem() {
showNoNotificationIntimation();
}
#Override
public void onUpdatedLogoutToServer() {
//if (SessionHelper.initializeSessionHelper().logout()) {
DisplayDialog.display(this);
/*} else {
Log.e("LogoutErr", "Homescreen: Unable to Logout");
}*/
}
#Override
public void onError(Exception e) {
Toast.makeText(getApplicationContext(), "Unable to logout from scheduler", Toast.LENGTH_SHORT).show();
}
when you delete item form list that time remove that item form list and notify adapter.
like below code ... when i am delete any item form recycler view ..
yourlist.remove(yourlist.get(yourlist.indexOf(data))); // common data that pass in list.if List<String> that pass string data if object them pass that object data.
youradapter.notifyDataSetChanged();
As per documentation you should not use this method with viewholder. you should use getAdapterposition() to get position of row.
getLayoutPosition added in version 22.1.0
int getLayoutPosition ()
Returns the position of the ViewHolder in terms of the latest layout
pass.
This position is mostly used by RecyclerView components to be
consistent while RecyclerView lazily processes adapter updates.
For performance and animation reasons, RecyclerView batches all
adapter updates until the next layout pass. This may cause mismatches
between the Adapter position of the item and the position it had in
the latest layout calculations.
LayoutManagers should always call this method while doing calculations
based on item positions. All methods in RecyclerView.LayoutManager,
RecyclerView.State, RecyclerView.Recycler that receive a position
expect it to be the layout position of the item.
If LayoutManager needs to call an external method that requires the
adapter position of the item, it can use getAdapterPosition() or
convertPreLayoutPositionToPostLayout(int).
In your use case, since your data is related to your adapter contents (and I assume that data is changed at the same time with adapter changes), you should be using adapterPosition.
Replace this lines
listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getLayoutPosition()));
listAdapter.notifyItemRemoved(viewHolder.getLayoutPosition());
with
listAdapter.getEntries().remove(listAdapter.getEntries().get(viewHolder.getAdapterPosition()));
listAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
I have an activity that manages instances of some sequential fragments and a ViewPager whose adapter is of type FragmentStatePagerAdapter. This fragments are sequentials because I want to create a sort of wizard that people must follow. All works fine, but I want to disable swipe when user wants to go to the next page (fragment) of the wizard if he has not completed all the fields in the current page.
package edu.polimi.dima.home121;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import edu.polimi.dima.home121.model.Place;
/**
* Created by leo on 13/01/2015.
*/
public class NewPlaceActivity extends ActionBarActivity
implements NewPlaceSummaryFragment.OnFragmentInteractionListener,
NewPlaceWizardFirstStepFragment.OnFragmentInteractionListener,
NewPlaceWizardSecondStepFragment.OnFragmentInteractionListener,
NewPlaceWizardThirdStepFragment.OnFragmentInteractionListener,
NewPlaceWizardFourthStepFragment.OnFragmentInteractionListener {
private final String TAG = getClass().getSimpleName();
private static Place place;
private static final int NUM_PAGES = 7;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
place = new Place();
setContentView(R.layout.activity_new_place);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(), mPager, place);
mPager.setAdapter(mPagerAdapter);
/*if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.newPlaceContainer, NewPlaceSummaryFragment.newInstance(place))
.commit();
}*/
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
#Override
public void onFragmentInteraction(Uri uri) {
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private Place place;
private ViewPager mPager;
public ScreenSlidePagerAdapter(FragmentManager fm, ViewPager mPager, Place place) {
super(fm);
this.place = place;
this.mPager = mPager;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new NewPlace0();
case 1:
NewPlaceWizardFirstStepFragment f1 = new NewPlaceWizardFirstStepFragment().newInstance(place);
f1.setPager(mPager);
return f1;
case 2:
NewPlaceWizardSecondStepFragment f2 = new NewPlaceWizardSecondStepFragment().newInstance(place);
f2.setPager(mPager);
return f2;
case 3:
NewPlaceWizardThirdStepFragment f3 = new NewPlaceWizardThirdStepFragment().newInstance(place);
f3.setPager(mPager);
return f3;
case 4:
NewPlaceWizardFourthStepFragment f4 = new NewPlaceWizardFourthStepFragment().newInstance(place);
f4.setPager(mPager);
return f4;
case 5:
NewPlace99 f5 = new NewPlace99();
return f5;
case 6:
NewPlaceSaving last = NewPlaceSaving.newInstance(place);
return last;
default:
return null;
}
}
#Override
public int getCount() {
//TODO sistemare il conteggio delle pagine
return NUM_PAGES;
}
}
}
For example the first fragment I have is:
public class NewPlaceWizardFirstStepFragment extends Fragment implements View.OnClickListener,
DialogInterface.OnClickListener {
private final String TAG = this.getClass().getSimpleName();
private static Place place;
private OnFragmentInteractionListener mListener;
private static View view;
private ViewPager pager;
public NewPlaceWizardFirstStepFragment() {
}
private TextView lblAvailableFrom;
private Button btnSingleRoom;
private Button btnDoubleRoom;
private Button btnStudioFlat;
private Button btnApartment;
private Button btnChangeDate;
private Button btnNext;
private EditText tfStreet;
private EditText tfCivic;
private EditText tfStair;
private EditText tfFloor;
private EditText tfCity;
private EditText tfPostalCode;
public static NewPlaceWizardFirstStepFragment newInstance(Place place) {
NewPlaceWizardFirstStepFragment fragment = new NewPlaceWizardFirstStepFragment();
fragment.place = place;
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_new_place_wizard_first_step, container, false);
setupUI();
return view;
}
public void setupUI() {
btnNext = (Button) view.findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
btnSingleRoom = (Button) view.findViewById(R.id.btnSingleRoom);
btnSingleRoom.setOnClickListener(this);
btnDoubleRoom = (Button) view.findViewById(R.id.btnDoubleRoom);
btnDoubleRoom.setOnClickListener(this);
btnStudioFlat = (Button) view.findViewById(R.id.btnStudioFlat);
btnStudioFlat.setOnClickListener(this);
btnApartment = (Button) view.findViewById(R.id.btnApartment);
btnApartment.setOnClickListener(this);
btnChangeDate = (Button) view.findViewById(R.id.changeDate);
btnChangeDate.setOnClickListener(this);
lblAvailableFrom = (TextView) view.findViewById(R.id.lblAvailableFrom);
tfStreet = (EditText) view.findViewById(R.id.tfStreet);
tfCivic = (EditText) view.findViewById(R.id.tfCivic);
tfStair = (EditText) view.findViewById(R.id.tfStair);
tfFloor = (EditText) view.findViewById(R.id.tfFloor);
tfCity = (EditText) view.findViewById(R.id.tfCity);
tfPostalCode = (EditText) view.findViewById(R.id.tfPostalAddress);
}
AlertDialog availableFromDialog;
private boolean enoughDataToContinue() {
boolean ret = true;
ret &= tfStreet.getText().length() != 0;
ret &= tfCivic.getText().length() != 0;
ret &= tfCity.getText().length() != 0;
return ret;
}
private void collectUserData() {
Address a = new Address();
a.setStreet(String.valueOf(tfStreet.getText()));
a.setNumber(String.valueOf(tfCivic.getText()));
a.setFloor(String.valueOf(tfFloor.getText()));
a.setStair(String.valueOf(tfStair.getText()));
a.setCity(String.valueOf(tfCity.getText()));
a.setPostalCode(String.valueOf(tfPostalCode.getText()));
place.setApartment(new Apartment());
place.getApartment().setAddress(a);
MiscServices.setCoordinates(place.getApartment());
Log.d(TAG, "first step done:" + new ObjectMapper().convertValue(place, Map.class).toString());
}
//TODO aggionare il toast
private void notifyUserOfInputIssues() {
Toast.makeText(getActivity().getApplicationContext(), "Complete all the fields to continue",
Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnNext:
if (enoughDataToContinue()) {
collectUserData();
pager.setCurrentItem(pager.getCurrentItem() + 1, true);
}
else
notifyUserOfInputIssues();
break;
case R.id.changeDate:
AvailableFromDialogBuilder availableFromDialogBuilder = new AvailableFromDialogBuilder(getActivity());
if (place.getAvailableFrom() != null)
availableFromDialogBuilder.setValue(place.getAvailableFrom());
availableFromDialogBuilder.setPositiveButton(R.string.my_continue, this);
availableFromDialog = availableFromDialogBuilder.show();
break;
case R.id.btnSingleRoom:
Log.v(TAG, "SingleRoom pressed");
clearSelection();
btnSingleRoom.setSelected(true);
place.setAccomodationType(Place.SINGLE_ROOM);
break;
case R.id.btnDoubleRoom:
Log.v(TAG, "DoubleRoom pressed");
clearSelection();
btnDoubleRoom.setSelected(true);
place.setAccomodationType(Place.DOUBLE_ROOM);
break;
case R.id.btnApartment:
Log.v(TAG, "Apartment pressed");
clearSelection();
btnApartment.setSelected(true);
place.setAccomodationType(Place.STANDARD_RENT);
break;
case R.id.btnStudioFlat:
Log.v(TAG, "StudioFlat pressed");
clearSelection();
btnStudioFlat.setSelected(true);
place.setAccomodationType(Place.STUDIO_FLAT);
break;
default:
Log.e(TAG, getResources().getString(R.string.error_ID) + v.getId());
}
}
public void clearSelection() {
btnApartment.setSelected(false);
btnSingleRoom.setSelected(false);
btnDoubleRoom.setSelected(false);
btnStudioFlat.setSelected(false);
}
;
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog == availableFromDialog) {
DatePicker datePicker = (DatePicker) availableFromDialog.findViewById(R.id.dpAvailableFrom);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
cal.set(Calendar.MONTH, datePicker.getMonth());
cal.set(Calendar.YEAR, datePicker.getYear());
place.setAvailableFrom(cal.getTime());
lblAvailableFrom.setText(datePicker.getDayOfMonth() + " - " + cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, getResources().getConfiguration().locale) + " - " + datePicker.getYear());
} else Log.e(TAG, getResources().getString(R.string.error_dialog));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public void setPager(ViewPager pager) {
this.pager = pager;
}
public ViewPager getPager() {
return pager;
}
public interface OnFragmentInteractionListener {
// TODO: valutare se serve
public void onFragmentInteraction(Uri uri);
}
}
How can I disable the swipe to the next fragment (right to left) even if the backward swipe (left to right) must be always enabled?
First, a little advice; For each of the following lines, there is no need to new since the method is static:
NewPlaceWizardFirstStepFragment f1 = NewPlaceWizardFirstStepFragment.newInstance(place);
That said, I'd probably just add some logic to your pager adapter to limit the count by the number of completed pages. i.e. If you're on step 4, count is 4. Upon completing step 4, increment the count to allow the user to swipe to the next fragment.
See this stack overflow post for an example:
ViewPager disable swiping to a certain direction
The best way to block page swipe is to control if edit text is filled inside onPageScrolled in PageViewActivity.java (my MainActivity)
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Log.i("test", "onPageScrolled - position = " + position);
currentPage = position;
txt1 = (EditText) findViewById(R.id.name_input);
if(position == 0) {
if(txt1.getText().toString().trim().length() == 0) {
pager.setCurrentItem(0);
} else if(txt1.getText().toString().trim().length() > 0) {
// DO NOTHING
}
}
}
i've recently started developing in android and am currently stuck at a point i need to receive values from a dialog box. I have a mainActivity which extends fragmentActivity and an AlertDialog Class.
1)i created a static method showDefalutDialog in AlertDialog class and its being called from mainActivity button click listener with parameters being passed to alertDialog.
2)In showDefalutDialog static method i created .setPositivebutton and .setNegativeButton with a Yes/No DialogInterface respectively.
now here's what i want to do.
1)When yes button on interface is clicked it should return a value to mainActivity
so i can implement it in an if statement to perform a certain function.
moving from windows c# programming doing so isn't a problem but i just don't know how to implement that in android below is relevant code snip
private void sendSms()
{
SharedPreferences pref = getApplicationContext().getSharedPreferences("Sms_MyPref", 0);
mail = pref.getString("email", null); // getting String
tel = pref.getString("receiver_tel", null); // getting String
layout = (LinearLayout)findViewById(R.id.linearLayout1);
from_dateEdit = (EditText) findViewById(R.id.date_edit);
to_dateEdit = (EditText) findViewById(R.id.date_edit_to);
snButton = (Button)findViewById(R.id.form_send_button);
from = (Button)findViewById(R.id.from);
to = (Button)findViewById(R.id.to);
spn = (Spinner)findViewById(R.id.form_spinner);
spn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
spinnerV = (String) item;
if(pos == 0)
{
layout.setVisibility( pos == 0 ? View.VISIBLE : View.VISIBLE);
from_dateEdit.setText(DatePickerFragment.getYesteesDate());
from.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDatePicker();
}
});
to_dateEdit.setText(DatePickerFragment.getTodaysDate());
to.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDatePicker2();
}
});
new1 = null;
new2 = null;
from_dateEdit.setText(new1);
to_dateEdit.setText(new2);
}
else if(pos == 1)
{
layout.setVisibility( pos == 1 ? View.GONE : View.VISIBLE);
new1 = null;
new2 = null;
new1 = "a";
new2 = "b";
}
else if(pos == 2)
{
layout.setVisibility( pos == 2 ? View.GONE : View.VISIBLE);
new1 = null;
new2 = null;
new1 = "a";
new2 = "b";
}
else if(pos == 3)
{
layout.setVisibility( pos == 3 ? View.GONE : View.VISIBLE);
new1 = null;
new2 = null;
new1 = "a";
new2 = "b";
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
snButton.setOnClickListener(new OnClickListener() {
public void onClick(View view)
{
if(new1 == null && new2 == null)
{
alert.showAlertDialog(MainActivity.this, "Error..", "Please specify a date range", false);
}
else if(new1 != null && new2 == null)
{
alert.showAlertDialog(MainActivity.this, "Error..", "Please specify a date TO", false);
}
else if(new1 == null && new2 != null)
{
alert.showAlertDialog(MainActivity.this, "Error..", "Please specify a date FROM", false);
}
else
{
gen = new1.toString()+","+new2.toString();
alert();
//i want to return a value from dialog yes/no click
if(/*dialog yes is clicked*/)
{
sms();
}
else if(/*dialog No is clicked*/)
{
return;
}
}
}
});
}
private void alert()
{
AlertDialogManager.showDefalutDialog(getApplicationContext(), spinnerV, mail, new1,new2);
}
public void sms()
{
String both = "{"+ spinnerV.toString() + ","+gen.toString()+","+ mail.toString()+"}";
sendSMS(tel,both);
}
and showDefaultDialog static method from AlertDialog class
#SuppressLint("InflateParams")
public static void showDefalutDialog(final Context context, String order, final String mail, String fromD, String toD) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle(R.string.finalmsg);
LayoutInflater li = LayoutInflater.from(context);
View view = li.inflate(R.layout.data_summary_view, null);
EditText EMAIL = (EditText)view.findViewById(R.id.Email);
EditText Selectedorder = (EditText)view.findViewById(R.id.order);
EditText Dfrom = (EditText)view.findViewById(R.id.edit_from);
EditText Dto= (EditText)view.findViewById(R.id.edit_to);
LinearLayout ll = (LinearLayout) view.findViewById(R.id.datelayout);
LinearLayout l2 = (LinearLayout) view.findViewById(R.id.datelayout2);
Selectedorder.setText(order);
EMAIL.setText(mail);
if(fromD.toString() != "a" && toD.toString() != "b")
{
ll.setVisibility(View.VISIBLE);
l2.setVisibility(View.VISIBLE);
Dfrom.setText(fromD);
Dto.setText(toD);
}
else if(fromD.toString() == "a" && toD.toString() == "b")
{
ll.setVisibility(View.GONE);
l2.setVisibility(View.GONE);
}
// set dialog message
alertDialogBuilder.setView(view);
//int msdt = data.toString().toCharArray().length;
//Toast.makeText(context, "MsData char count : " + msdt , Toast.LENGTH_SHORT).show();;
alertDialogBuilder
.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
try {
Intent main = new Intent(context, MainActivity.class);
main.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(main);
} catch (Exception e) {
Log.d(TAG, "Error while starting Main activity from Dialog ! ");
}
}
})
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Toast.makeText(context,"Your Order will be sent to "+ mail +" please check your inbox for comfirmation." , Toast.LENGTH_SHORT).show();
dialog.cancel();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.dismiss();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
You can define you custom interface simmilar to this one:
public interface MyDialogClickListener {
void onPositiveClicked(String value);
}
Then you create instance and pass to method, where you create dialog:
public static void showDeafultDialog(..., MyDialogClickListener listener) {
// ...
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
listener.onPositiveClicked("you can pass yout value here")
}
})
// ...
}
Handle result:
private void sendSms() {
AlertDialogManager.showDeafultDialog(..., new MyDialogClickListener() {
#Override
public void onPositiveClicked(String value) {
// do whatever you want with value
}
});