Disable Scroll left in ViewPager Android Studio - java

I know this is common to ask but still I'm confused how can I disable scroll to left from ViewPager, What I'm trying to do is when the input field/household field is empty you cannot procced to the next part, currently it works on the button when I'm trying to click next button it will pops Toast, but when I scroll using my finger it didn't work since I didn't applied it yet, can anyone explain or how can I achieve this? I'm struggling with this one.
OnBoardingScreen - Java
private TextView tvNext, tvSkip;
private ViewPager viewPager;
private LinearLayout layoutDots;
private IntroPref introPref;
private int[] layouts;
private TextView[] dots;
private MyViewPagerAdapter viewPagerAdapter;
EditText edt_hh;
tvNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edt_hh = findViewById(R.id.edt_hh_no);
household = edt_hh.getText().toString();
int current = getItem(+1);
//
if (household.matches("")){
Toasty.error(getApplicationContext(),"Required", Toasty.LENGTH_SHORT).show();
}
else if (current < layouts.length) {
viewPager.setCurrentItem(current);
}
else {
launchHomeScreen();
}
}
});
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addBottomDots(position);
edt_hh = findViewById(R.id.edt_hh_no);
household = edt_hh.getText().toString();
if (household.matches("")){
Toasty.error(getApplicationContext(),"Required", Toasty.LENGTH_SHORT).show();
}
else if (position == layouts.length - 1) {
tvNext.setText("SCAN");
} else {
tvNext.setText("NEXT");
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] activeColors = getResources().getIntArray(R.array.active);
int[] inActiveColors = getResources().getIntArray(R.array.inactive);
layoutDots.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("&#8226"));
dots[i].setTextSize(50);
dots[i].setTextColor(inActiveColors[currentPage]);
layoutDots.addView(dots[i]);
}
if (dots.length > 0) {
dots[currentPage].setTextColor(activeColors[currentPage]);
}
}
public class MyViewPagerAdapter extends PagerAdapter {
LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
View view = (View) object;
container.removeView(view);
}
}
private int getItem(int i) {
return viewPager.getCurrentItem() + 1;
}
private void launchHomeScreen() {
showImageImportDialog();
}
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
xml
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Now it is possible to enable-disable swiping viewpager2
https://developer.android.com/guide/navigation/navigation-swipe-view-2
Note: If your app already uses ViewPager, see Migrate from ViewPager to ViewPager2.
Sample code to disable swiping in viewpager2
myViewPager2.setUserInputEnabled(false);
Sample code to enable swiping in viewpager2
myViewPager2.setUserInputEnabled(true);

You can disable your view pager scroll using custom ViewPager :
Is it possible to disable scrolling on a ViewPager

Related

How can I de-select recyclerView Item onSwiped?

I have a fragment with a recyclerView.
A user is allowed to delete an exercise logEntry by swiping right.
A user can also update a logEntry by clicking on the recyclerView item.
(This highlights the current selected item green, hides the clear button and converts the save button to an update button.)
To deselect the item , the user can click on the recyclerView a second time.
Unfortunately, if a user was to select an item and then decides to swipe to delete an item, the recyclerView item which takes the same position as the originally selected item is remains highlighted green.
When a user swipes to delete an item, I would like the background of all recyclerView items to be reset to grey.
How could this be done?
Relevant Fragment Code
OnExerciseClicked
#Override
public void onExerciseClicked(int position) {
if (recyclerItemClicked == false) {
saveBtn.setText("Update");
clearBtn.setVisibility(View.GONE);
recyclerItemClicked = true;
double selectedWeight = adapter.getWeight(position);
String selectedWeightString = Double.toString(selectedWeight);
editTextWeight.setText(selectedWeightString);
int selectedReps = adapter.getReps(position);
String selectedRepsString = Integer.toString(selectedReps);
editTextReps.setText(selectedRepsString);
} else {
clearBtn.setVisibility(View.VISIBLE);
saveBtn.setText("Save");
recyclerItemClicked = false;
}
}
OnSwiped
ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
int logID = allExercises.get(viewHolder.getAdapterPosition()).getLog_id();
logViewModel.deleteByID(logID);
clearBtn.setVisibility(View.VISIBLE);
saveBtn.setText("Save");
adapter.notifyDataSetChanged();
}
};
Adapter
public class CompletedExercisesListAdapter2 extends RecyclerView.Adapter {
private OnExerciseClickListener onExerciseClickListener;
private List<Log_Entries> allCompletedExercises = new ArrayList<>();
private int adapterPos = -1;
public boolean flag = false;
public CompletedExercisesListAdapter2(ArrayList<Log_Entries> allCompletedExercises, OnExerciseClickListener onExerciseClickListener) {
this.allCompletedExercises = allCompletedExercises;
this.onExerciseClickListener = onExerciseClickListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view;
if (viewType == 0) {
view = layoutInflater.inflate(R.layout.new_completed_exercise_item, parent, false);
return new ViewHolderOne(view, onExerciseClickListener);
}
view = layoutInflater.inflate(R.layout.completed_exercise_item, parent, false);
return new ViewHolderTwo(view, onExerciseClickListener);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if (getItemViewType(position) == 0) {
ViewHolderOne viewHolderOne = (ViewHolderOne) holder;
if (adapterPos == position) {
viewHolderOne.relativeLayout.setBackgroundColor(Color.parseColor("#567845"));
} else {
viewHolderOne.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
viewHolderOne.textViewExerciseName.setText(String.valueOf(allCompletedExercises.get(position).getChildExerciseName()));
//viewHolderOne.textViewSetNumber.setText(String.valueOf(allCompletedExercises.get(position).getSet_number()));
viewHolderOne.textViewSetNumber.setText(String.valueOf(viewHolderOne.getAdapterPosition() + 1));
viewHolderOne.textViewWeight.setText(String.valueOf(allCompletedExercises.get(position).getTotal_weight_lifted()));
viewHolderOne.textViewReps.setText(String.valueOf(allCompletedExercises.get(position).getReps()));
} else if (getItemViewType(position) == 1) {
ViewHolderTwo viewHolderTwo = (ViewHolderTwo) holder;
if (adapterPos == position) {
viewHolderTwo.relativeLayout.setBackgroundColor(Color.parseColor("#567845"));
} else {
viewHolderTwo.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
// viewHolderTwo.textViewSetNumber.setText(String.valueOf(allCompletedExercises.get(position).getSet_number()));
viewHolderTwo.textViewSetNumber.setText(String.valueOf(viewHolderTwo.getAdapterPosition() + 1));
viewHolderTwo.textViewWeight.setText(String.valueOf(allCompletedExercises.get(position).getTotal_weight_lifted()));
viewHolderTwo.textViewReps.setText(String.valueOf(allCompletedExercises.get(position).getReps()));
}
}
#Override
public int getItemCount() {
return allCompletedExercises.size();
}
#Override
public int getItemViewType(int position) {
// if list is sorted chronologically
if (position == 0) {
return 0;
}
if (allCompletedExercises.get(position).getChildExerciseName().equals(allCompletedExercises.get(position - 1).getChildExerciseName())) {
return 1;
} else {
return 0;
}
}
class ViewHolderOne extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewExerciseName;
private TextView textViewSetNumber;
private TextView textViewWeight;
private TextView textViewReps;
OnExerciseClickListener mOnExerciseClickListener;
private RelativeLayout relativeLayout;
public ViewHolderOne(#NonNull View itemView, OnExerciseClickListener onExerciseClickListener) {
super(itemView);
textViewExerciseName = itemView.findViewById(R.id.textView_ExerciseName3);
textViewSetNumber = itemView.findViewById(R.id.textView_Set_Number56);
textViewWeight = itemView.findViewById(R.id.textView_weight78);
textViewReps = itemView.findViewById(R.id.textView_repss0);
mOnExerciseClickListener = onExerciseClickListener;
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.exercise_item_relative);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExerciseClickListener.onExerciseClicked(getAdapterPosition());
if (flag) {
adapterPos = -1;
flag = false;
} else {
adapterPos = getAdapterPosition();
flag = true;
}
notifyDataSetChanged();
}
}
class ViewHolderTwo extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewSetNumber;
private TextView textViewWeight;
private TextView textViewReps;
OnExerciseClickListener mOnExerciseClickListener;
private RelativeLayout relativeLayout;
public ViewHolderTwo(#NonNull View itemView, OnExerciseClickListener onExerciseClickListener) {
super(itemView);
textViewSetNumber = itemView.findViewById(R.id.textView_Set_Number);
textViewWeight = itemView.findViewById(R.id.textView_weight);
textViewReps = itemView.findViewById(R.id.textView_repss);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.exercise_item_rel);
mOnExerciseClickListener = onExerciseClickListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExerciseClickListener.onExerciseClicked(getAdapterPosition());
if (!flag) {
adapterPos = getAdapterPosition();
flag = true;
} else {
adapterPos = -1;
flag = false;
}
notifyDataSetChanged();
}
}
public interface OnExerciseClickListener {
void onExerciseClicked(int position);
}
public double getWeight(int position) {
double weight = allCompletedExercises.get(position).getTotal_weight_lifted();
return weight;
}
public int getReps(int position) {
int reps = allCompletedExercises.get(position).getReps();
return reps;
}
}
I highly recommend using a library like Groupie to abstract away the complicated state management of RecyclerView. Otherwise you'll find this imperative style quickly becomes unmaintainable. The future is declarative UI (Compose etc). This way it is much easier to keep track of Items rather than positions.
It's quite hard to follow your code (you should use descriptive names for things, like isSelected instead of flag). However I think your problem lies in your bind function not returning false here:
if (adapterPos == position)
after you swipe. Use break points to work out why

ExpandableRecyclerView - How to expand and collapse multiple CardViews simultaneously

Is it possible to expand and collapse multiple CardViews within a RecyclerView at the same time? I created a header (for my RecyclerView) with two buttons but I'm not sure what needs to go in the click event.
RecyclerView adapter class
public class MyRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
public boolean isSupposedToBeCollapsed;
private Context mContext;
RecyclerViewHeader header;
List<RecyclerViewItem> listItems;
ValueAnimator mAnimator;
public MyRecyclerAdapter(Context context, RecyclerViewHeader header, List<RecyclerViewItem> listItems)
{
this.mContext = context;
this.header = header;
this.listItems = listItems;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_HEADER)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_header, parent, false);
return new MyRecyclerAdapter.VHHeader(v);
}
else if(viewType == TYPE_ITEM)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
return new MyRecyclerAdapter.VHItem(v);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
private RecyclerViewItem getItem(int position)
{
return listItems.get(position);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Typeface iconFont = FontManager.getTypeface(mContext, FontManager.FONTAWESOME);
if (holder instanceof VHHeader)
{
final VHHeader vhHeader = (VHHeader)holder;
vhHeader.btnExpandAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isSupposedToBeCollapsed){
// change visibility to 'VISIBLE'
txtB.setVisibility(View.VISIBLE);
// change direction of chevron to 'up'
txtExpandCollapse.setText(R.string.fa_icon_chevron_up);
// apply animation to the height of 'txtB'
mAnimator = slideAnimator(0, textBHeight);
// start the animation
mAnimator.start();
}
else{
}
}
});
vhHeader.btnCollapseAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isSupposedToBeCollapsed){
// change visibility to 'VISIBLE'
txtB.setVisibility(View.VISIBLE);
// change direction of chevron to 'up'
txtExpandCollapse.setText(R.string.fa_icon_chevron_up);
// apply animation to the height of 'txtB'
mAnimator = slideAnimator(0, textBHeight);
// start the animation
mAnimator.start();
}
else{
}
}
});
}
else if (holder instanceof VHItem)
{
RecyclerViewItem currentItem = getItem(position-1);
final VHItem vhItem = (VHItem)holder;
vhItem.txtA.setText(currentItem.getTitle());
vhItem.txtB.setText(currentItem.getDescription());
vhItem.txtB.setVisibility(View.GONE);
vhItem.txtExpandCollapse.setText(R.string.fa_icon_chevron_down);
vhItem.txtExpandCollapse.setTypeface(iconFont);
//Add onPreDrawListener
vhItem.txtB.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
vhItem.txtB.getViewTreeObserver().removeOnPreDrawListener(this);
vhItem.txtB.setVisibility(View.GONE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
vhItem.txtB.measure(widthSpec, heightSpec);
vhItem.textBHeight = vhItem.txtB.getMeasuredHeight();
return true;
}
});
vhItem.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(vhItem.txtB.getVisibility() == View.GONE){
vhItem.expand();
} else {
vhItem.collapse();
}
}
});
vhItem.mLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(vhItem.txtB.getVisibility() == View.GONE){
vhItem.expand();
} else {
vhItem.collapse();
}
}
});
vhItem.txtExpandCollapse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(vhItem.txtB.getVisibility() == View.GONE){
vhItem.expand();
} else {
vhItem.collapse();
}
}
});
}
}
// need to override this method
#Override
public int getItemViewType(int position) {
if(isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position)
{
return position == 0;
}
// increasing getItemcount to 1. This will be the row of header.
#Override
public int getItemCount() {
return listItems.size()+1;
}
class VHHeader extends RecyclerView.ViewHolder{
Button btnCollapseAll, btnExpandAll;
public VHHeader(View headerView) {
super(headerView);
this.btnCollapseAll = headerView.findViewById(R.id.btn_collapseall);
this.btnExpandAll = headerView.findViewById(R.id.btn_expandall);
}
}
public class VHItem extends RecyclerView.ViewHolder{
CardView cardView;
LinearLayout mLinearLayout;
RecyclerView mRecyclerView;
RelativeLayout mRelativeLayout;
TextView txtExpandCollapse, txtA, txtB;
public int textBHeight;
public VHItem(View itemView) {
super(itemView);
this.cardView = itemView.findViewById(R.id.cv);
this.mLinearLayout = itemView.findViewById(R.id.cardview_tconnections_titlerow);
this.mRelativeLayout = itemView.findViewById(R.id.my_relativelayout);
this.mRecyclerView = itemView.findViewById(R.id.my_recyclerview);
this.txtExpandCollapse = itemView.findViewById(R.id.tv_expandcollapse);
this.txtA = itemView.findViewById(R.id.tv_A);
this.txtB = itemView.findViewById(R.id.tv_B);
}
private void expand() {
// change visibility to 'VISIBLE'
txtB.setVisibility(View.VISIBLE);
// change direction of chevron to 'up'
txtExpandCollapse.setText(R.string.fa_icon_chevron_up);
// apply animation to the height of 'txtB'
mAnimator = slideAnimator(0, textBHeight);
// start the animation
mAnimator.start();
}
private void collapse() {
// change direction of chevron to 'down'
txtExpandCollapse.setText(R.string.fa_icon_chevron_down);
int finalHeight = txtB.getHeight();
ValueAnimator mAnimator = slideAnimator(finalHeight, 0);
mAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationEnd(Animator animator) {
txtB.setVisibility(View.GONE);
}
#Override
public void onAnimationStart(Animator animator) {
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
}
});
mAnimator.start();
}
public ValueAnimator slideAnimator(int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
// update height
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = txtB.getLayoutParams();
layoutParams.height = value;
txtB.setLayoutParams(layoutParams);
}
});
return animator;
}
}
}
Fragment class
public class MyFragment extends android.support.v4.app.Fragment {
private MyRecyclerAdapter adapter;
public MyFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_rv, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
View v = getView();
assert v != null;
recyclerView = v.findViewById(R.id.my_recyclerview);
linearLayoutManager = new LinearLayoutManager(getActivity());
MyRecyclerAdapter adapter = new MyRecyclerAdapter(getContext(), getHeader(), getListItems());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
super.onActivityCreated(savedInstanceState);
}
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
public RecyclerViewHeader getHeader()
{
return new RecyclerViewHeader();
}
public List<RecyclerViewItem> getListItems()
{
List<RecyclerViewItem> rvItems = new ArrayList<>();
RecyclerViewItem itemA = new RecyclerViewItem();
itemA.setConnectionMode("Item A");
itemA.setConnectionName("Feature A1");
rvItems.add(itemA);
RecyclerViewItem itemB = new RecyclerViewItem();
itemB.setConnectionMode("Item B");
itemB.setConnectionName("Feature B1\nFeature B2");
rvItems.add(itemB);
RecyclerViewItem itemC = new RecyclerViewItem();
itemC.setConnectionMode("Item C");
itemC.setConnectionName("Feature C1\nFeature C2\nFeature C3");
rvItems.add(itemC);
return rvItems;
}
}
What you can do is, set a variable(boolean) that stores the state of the card (expanded/collapsed) in the RecyclerAdapter code.
Then, in your onBindViewHolder code block, write a piece of code to check if the card should be expanded or collapsed using the above-mentioned variable and the required display code.
Example:
if(isSuppossedToBeCollapsed){
textView.setVisibility = false;
}
else{
textView.setVisibility = true;
}
You can then call notifyDatasetChanged in your RecyclerAdapter code to update the recycler views when you click the button which will redraw the views and reflect the state of the cards(expanded/collapsed) accordingly.
NotifyDatasetChanged Documentation

How to rotate a list such that item selected from the list always gets the middle position in a list view

I don't know if I did any mistake while rotating the list or something else needs to be done..I would appreciate it very much if anyone could help me on figuring out the solution.
I have a vertical ListView with 5 items(in the left side of the screen-shots) as shown in the screen-shots:
As you can see the list should be rotated each time an item is clicked or selected.The problem is that the code that i have implemented works with onItemClickListener(when the item clicked is one position below or above the item in the middle),but it doesn't work with onItemSelectedListener(the list rotates for two times (for a single direction) then stops rotating in that direction, meaning onItemSelected is not called at all).
May be more screen shots will make it clear:
Well this might make you more confused though.. I want a list whose selected item takes the middle (Text Color Blue) position and the list rotates accordingly.
Please Help.... Thanks a Lot.
Source Code: Main Activity:
public class MainActivity extends AppCompatActivity {
private ListView categoryList;
ListCustomAdapter listadapter;
private List<TextItem> txtItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
categoryList = (ListView) findViewById(R.id.listCategories);
listadapter=new ListCustomAdapter(this,txtItems);
categoryList.setAdapter(listadapter);
categoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
listadapter.getPosition(i);
Log.d("position",""+i);
if(i>2) {
Log.d("position1",""+(i-1));
Collections.rotate(txtItems, 4);
listadapter.notifyDataSetChanged();
}else if(i<2){
Log.d("position2",""+(1-i));
Collections.rotate( txtItems,1);
listadapter.notifyDataSetChanged();
}
else{
}
}
});
categoryList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("inside" ,"onItemSelected");
if(i>2) {
Collections.rotate(txtItems,4);
Log.d("position rotated",""+i);
listadapter.notifyDataSetChanged();
}else if(i<2){
Collections.rotate( txtItems,1);
listadapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
Log.e("inside" ,"onNothingSelected");
}
});
}
ListCustomAdapter:
public class ListCustomAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<TextItem> txtItems;
int pos;
public ListCustomAdapter(Activity activity, List<TextItem> txtItems) {
this.activity = activity;
this.txtItems = txtItems;
}
#Override
public int getCount() {
return txtItems.size();
}
#Override
public Object getItem(int location) {
return txtItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
/*
inflate the items in the list view
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.vertical_list_item, null);
holder = new ViewHolder();
holder.category = (TextView) convertView.findViewById(R.id.category_name);
holder.listLayout= (LinearLayout) convertView.findViewById(R.id.list_layout);
convertView.setTag(holder);
}else
{
holder = (ViewHolder) convertView.getTag();
}
if (pos == position) {
Log.d("translated","done of position"+pos);
holder.category.setTranslationX(10.17f);
} else {
/* view.imgViewFlag.getLayoutParams().height = 140;
view.imgViewFlag.getLayoutParams().width = 300;*/
holder.category.setTranslationX(1.0f);
Log.d("translated","default of position"+pos);
// view.imgViewFlag.setBackgroundResource(0);
holder.category.setBackgroundResource(0);
}
TextItem model = txtItems.get(position);
holder.category.setText(model.getTitleName());
if(position==2)
holder.category.setTextColor(Color.BLUE);
/*
creating objects to access the views
*/
return convertView;
}
public void getPosition(int position) {
this.pos = position;
}
static class ViewHolder {
TextView category;
LinearLayout listLayout;
}
}
Since my code works fine for OnItemClickListener, I figured out that the item that's clicked is set as selected in the list..so for OnItemSelectedListener... I had to make the middle position as selected all the time .. Hence,I added the following
categoryList.setSelection(2); /*2 is the mid position for the list with 5 items *\
after the list was rotated i.e:
categoryList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("inside" ,"onItemSelected");
if(i>2) {
Collections.rotate(txtItems,4);
categoryList.setSelection(2);
Log.d("position rotated",""+i);
listadapter.notifyDataSetChanged();
}else if(i<2){
Collections.rotate( txtItems,1);
categoryList.setSelection(2);
listadapter.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
Log.e("inside" ,"onNothingSelected");
}
});

Drag and drop from custom slider doesn't work

I'm trying to make a drag and drop from a custom slider.
The slider is in a viewPager and is shows Imageviews.
I don't know witch ID I should set to my longClickListener.
I tried the Imagview (swip_image_view) but it return null.
& it doesn't work with the viewpager.
Why is my longClickListener not working?
public class Activity_Kind extends Activity {
ViewPager viewPager;
CustomHorizontalSwip customHorizontalSwip;
private GridView gridDieren;
private ImageView bus;
private ImageView slider;
private TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kies_dier);
gridDieren = (GridView) findViewById(R.id.gridSelectDieren);
text = (TextView) findViewById(R.id.kiesdiertext);
bus = (ImageView) findViewById(R.id.imageBus);
viewPager = (ViewPager) findViewById(R.id.viewPager);
customHorizontalSwip = new CustomHorizontalSwip(this);
viewPager.setAdapter(customHorizontalSwip);
viewPager.setLongClickable(true);
viewPager.setOnLongClickListener(longClickListener);
//slider = (ImageView) findViewById(R.id.swip_image_view);
//slider.setOnLongClickListener(longClickListener);
bus.setOnDragListener(dragListener);
}
View.OnLongClickListener longClickListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder myShadowBuilder = new View.DragShadowBuilder(v);
v.startDrag(data, myShadowBuilder, v, 0);
return true;
}
};
View.OnDragListener dragListener = new View.OnDragListener() {
#Override
public boolean onDrag(View v, DragEvent event) {
int dragEvent = event.getAction();
switch (dragEvent) {
case DragEvent.ACTION_DRAG_ENTERED:
final View view = (View) event.getLocalState(); //Krijgt alle informatie van die view die wordt gedraged
if (view.getId() == R.id.imageBus);
text.setText("Werkt");
//gridDieren.addView(view);
break;
case DragEvent.ACTION_DRAG_ENDED:
break;
case DragEvent.ACTION_DROP:
break;
}
return true;
}
};
}
public class CustomHorizontalSwip extends PagerAdapter {
private int [] imageResources ={R.drawable.beer,R.drawable.bever, R.drawable.kip, R.drawable.leeuw, R.drawable.nijlpaard, R.drawable.poes
,R.drawable.ezel,R.drawable.hond, R.drawable.ooievaar, R.drawable.varken, R.drawable.wormpje};
private Context ctx;
private LayoutInflater layoutInflater;
public CustomHorizontalSwip(Context c) {
ctx=c;
}
#Override
public int getCount() {
return imageResources.length;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater= (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView=layoutInflater.inflate(R.layout.custom_swipe_dieren,container,false);
ImageView imageView=(ImageView) itemView.findViewById(R.id.swip_image_view);
imageView.setImageResource(imageResources[position]);
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view==object);
}
}
Your image swip_image_view is inside layout custom_swipe_dieren.xml. You should set onLongClickListener inside CustomHorizontalSwip -> instantiateItem() method like this :
public class CustomHorizontalSwip extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater= (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView=layoutInflater.inflate(R.layout.custom_swipe_dieren,container,false);
ImageView imageView=(ImageView) itemView.findViewById(R.id.swip_image_view);
imageView.setImageResource(imageResources[position]);
imageView.setOnLongClickListener(longClickListener);
container.addView(itemView);
return itemView;
}
/* Declare and Initialise longClickListener in this file also */
/* Also do same for dragListener in this file */
}
This will work for you
Thanks

Actionbar's onNavigationItemSelected(int position, long itemId) not triggered after horizontal swipe in Gingerbread

I have implemented Tab view as well as Horizontal swipe view(to change tabs) with Navigation mode as Lists for the application. I am using ActionBarSherlock & TabPageIndicator. I used fragments for reloading the contents after changing the tabs.
In drop down spinner, I have 2 items. These are getting selected whenever activity reloads or after hitting on Tabs.
But, if swipe is performed to select other tab, then onNavigationItemSelected(int position, long itemId) will not getting triggered in Gingerbread version :( We have tested it on Gingerbread 2.3.6, 2.3.3.
In logcat, I got this warning message "View:onTouchEvent:ViewFlags" is DISABLED
But, it works perfectly fine on ICS, Froyo, etc.
Your help would be greatly appreciated.
following is the code snippet:
public class MainPageActivity extends SherlockFragmentActivity implements
ActionBar.OnNavigationListener {
MenuItem menuItem;
EditText searchText;
public static Context mContext;
public static DataAdapter dataAdapter;
ArrayList<String> accountList;
public static List<View> currentViewBeingChanged = new ArrayList<View>();
public static LayoutInflater layoutInflater;
public static String checktab = "running", nameComp;
int isRefresh;
public static boolean isAutoRefresh = true;
public static ArrayList<String> listItems;
public static boolean check;
public static boolean isAtleastOnce = true, listToBeRefreshed = false;
public static ActionBar actionBar;
public static int itemPosition, listPosition;
public static FragmentManager fragmentManager;
InputMethodManager imm;
#Override
protected void onCreate(Bundle savedInstanceState) {
mContext = this;
layoutInflater = getLayoutInflater();
fragmentManager = getSupportFragmentManager();
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
Context context = getSupportActionBar().getThemedContext();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
android.R.layout.simple_spinner_dropdown_item);
adapter.clear();
for (int i = 0; i < ManageAccountLists.accountList.size(); i++) {
adapter.add(ManageAccountLists.accountList.get(i));
}
actionBar.setListNavigationCallbacks(adapter, this);
tabPagerFunction();
}
public void tabPagerFunction() {
FragmentPagerAdapter adapter = new GoogleMusicAdapter(
getSupportFragmentManager());
adapter.notifyDataSetChanged();
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
checktab = "running";
final TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(pager);
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
System.out.println("Tab selected..................");
if (arg0 == 0) {
// Running tab is selected
indicator.setCurrentItem(arg0);
checktab = "running";
RunningInstancesActivity runningInstancesActivity = new RunningInstancesActivity();
runningInstancesActivity.callThread();
} else {
// Stopped tab is selected
indicator.setCurrentItem(arg0);
checktab = "stopped";
StoppedInstancesActivity stoppedInstancesActivity = new StoppedInstancesActivity();
stoppedInstancesActivity.callThread();
InstanceStatusUpdate.isOnPostExecute = false;
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
class GoogleMusicAdapter extends FragmentPagerAdapter {
private final String[] CONTENT = new String[] { "Running", "Stopped" };
public GoogleMusicAdapter(FragmentManager fm) {
super(fm);
notifyDataSetChanged();
}
#Override
public Fragment getItem(int position) {
switch (position) {
/** Running tab is selected */
case 0:
checktab = "stopped";
return RunningInstancesActivity.newInstance(0);
/** Stopped tab is selected */
case 1:
checktab = "running";
return StoppedInstancesActivity.newInstance(1);
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
public CharSequence getPageTitle(int position, int number) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
#Override
public int getCount() {
return CONTENT.length;
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
System.out.println("Navigation item selected");
// Performs fetching
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
System.out.println("Dispatch touvh event..");
return super.dispatchTouchEvent(ev);
}
}
Try doing this
dependencies {
compile "com.android.support:appcompat-v7:18.0.+"
}
and use support library instead.
As far as I remember there were some issues with updating the navigation list after swiping (in ABS). This is what I did to solve this issue and it works with Android 2.3.7 (ABS) as well as with Android 4.0 (native AB).
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (navigatioBarIsUsed) actionBar.setSelectedNavigationItem(position);
if (tabsAreUsed) actionBar.getTabAt(position).select();
}
});
Internally it reselects the page - that's not so nice - however that was the only solution I found.
Cheers
Use This code..
Inside Your Fragment Use this code.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
// TODO Auto-generated method stub
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
Activity activity = getActivity();
ActionBar actionBar = ((ActionBarActivity) activity)
.getSupportActionBar();
actionBar.setIcon(getResources().getDrawable(R.drawable.nearby));
}
}

Categories