Android : spinner next index exit after last item - android

I have implemented a spinner that everytime when I click a button the next item will be selected. But my goal is when the last item is selected the activity should intent in the previous activity. Here is my code so far. I hope someone can help my problem
public void spinNext() {
int nextIndex = spinStudent.getSelectedItemPosition() + 1;
if (nextIndex < studentList.size()) {
spinStudent.setSelection(nextIndex);
}
}

When nextIndex reaches to last item call finish().
Do this
public void spinNext() {
int nextIndex = spinStudent.getSelectedItemPosition() + 1;
if (nextIndex < studentList.size()) {
spinStudent.setSelection(nextIndex);
}
else if(nextIndex == studentList.size()){
finish();
}
}

Try this:
int spinSize = spinStudent.getCount();
if(spinStudent.getSelectedItemPosition() == (spinSize -1))
{
finish();
}

Related

Video is not getting paused in ViewPager

I m using viewpager and its adapter i m displaying image and video as per condition.
I don't have fragment because i m using PagerAdapter.
Code:
pager.setOnPageChangeListener(pageChangeListener);
pager.post(new Runnable() {
#Override
public void run() {
pageChangeListener.onPageSelected(pager.getCurrentItem());
}
});
}
ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
View view = mediaFullScreenImageAdapter.getActiveView(pager);
if (selectedPhotosByDate.get(position).getMessagetype().equalsIgnoreCase("VIDEO")) {
CustomVideoPlayer video_player = (CustomVideoPlayer) view.findViewById(R.id.video_player);
if (video_player.isPlaying()) {
Log.v("THISCALLEDD", "Y" + " : " + position);
video_player.pause();
}
}
}
};
#Nullable
public View getActiveView(final ViewPager viewPager) {
final PagerAdapter adapter = viewPager.getAdapter();
if (null == adapter || adapter.getCount() == 0 || viewPager.getChildCount() == 0) {
return null;
}
int position;
final int currentPosition = viewPager.getCurrentItem();
for (int i = 0; i < viewPager.getChildCount(); i++) {
final View child = viewPager.getChildAt(i);
final ViewPager.LayoutParams layoutParams = (ViewPager.LayoutParams) child.getLayoutParams();
if (layoutParams.isDecor) {
continue;
}
final Field positionField;
try {
positionField = ViewPager.LayoutParams.class.getDeclaredField("position");
positionField.setAccessible(true);
position = positionField.getInt(layoutParams);
} catch (NoSuchFieldException e) {
break;
} catch (IllegalAccessException e) {
break;
}
if (position == currentPosition) {
return child;
}
}
return null;
}
Update:
selectedPhotosByDate = appDatabase.chatMessagesDao().getMediaByGroupId(topicid, "Y");
if (selectedPhotosByDate.size() > 0 && selectedPhotosByDate != null) {
mediaFullScreenImageAdapter = new MediaFullScreenImageAdapter(MediaFullScreenSlideActivity.this, selectedPhotosByDate);
pager.setAdapter(mediaFullScreenImageAdapter);
for (int i = 0; i < selectedPhotosByDate.size(); i++) {
if (messageid == selectedPhotosByDate.get(i).getMessageId()) {
position = i;
break;
}
}
pager.setCurrentItem(position);
pager.setOffscreenPageLimit(selectedPhotosByDate.size());
}
I am able to get logcat value . But my video doesn't get pause.
If my video is playing and user swipe for other item playing video must be paused.
Advanced help would be appreciated!
Based on the documentation here, onPageSelected is called when a new page is selected. That means, the active view that you are trying to get using the currentItem from the ViewPager will return you the current selected item rather than the previously selected item. So your reference to video_player is also wrong and hence it is not working.
A simple way to do this is to have a variable currentPosition. Update it in onPageSelected but before updating, get its view and pause the video. This way whenever you access it, you will first get the previous index and then you will update it to the current index for the next time.
As per my understanding ,you want to pause previous video when user swipe in viewpager .
#Override
public void onPageSelected(int position) {
View view = mediaFullScreenImageAdapter.getActiveView(pager);
if (selectedPhotosByDate.get(position).getMessagetype().equalsIgnoreCase("VIDEO")) {
CustomVideoPlayer video_player = (CustomVideoPlayer) view.findViewById(R.id.video_player);
if (video_player.isPlaying()) {
Log.v("THISCALLEDD", "Y" + " : " + position);
video_player.pause();
}
}
}
you are getting view object of current active position ,but you want to pause video of (position - 1 ),you need to have view object of previous position .
Finally resolved the issue.
I moved this code
View view = mediaFullScreenImageAdapter.getActiveView(pager);
CustomVideoPlayer video_player = (CustomVideoPlayer) view.findViewById(R.id.video_player);
video_player.pause();
to onPageScrolled() method instead of onPageSelected() method.
This worked for me with a Youtube video playing as an embedded iFrame in a WebView:
viewPager.addOnPageChangeListener(object : SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
// NOTE: this workaround pauses any playing Youtube video in the WebView, if the video screen is being switched out.
// This works by getting the ViewPager#focusedChild, which will be the WebView if that screen is currently in focus,
// before the next selected ViewPager screen gets switched-to/loaded.
viewPager.focusedChild?.findViewById<WebView>(R.id.video_view)?.onPause()
// NOTE: we do a postDelay below, to ensure the WebView gets put back into its resume state, if it being switched to.
// This is delayed, so that this happens after the ViewPager screen with the WebView, has time to load it into place.
postDelayed({ viewPager.focusedChild?.findViewById<WebView>(R.id.video_view)?.onResume() }, 200)
}
})

Is there a way to prevent the gridview from scrolling to its top position when its adapter's data is changed?

after loading more data the grid view back to top, I want to make it keep scrolling from the last item after loading.
I tried to use onScrollStateChanged, and make it loading in state == SCROLL_STATE_TOUCH_SCROLL, but I faced the same problem.
#Override
protected void onPostExecute(ArrayList<productDetails> AProducts) {
final ArrayList<productDetails> products = AProducts;
super.onPostExecute(products);
productAdapter = new productAdapter(category.this, productDetailsArr);
gridView.setAdapter(productAdapter);
productAdapter.notifyDataSetChanged();
if (products != null) {
gridView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount) {
// End has been reached
limit = Integer.parseInt(((productDetails) (products.get(products.size() - 1))).getProductID());
// limit = Integer.parseInt(products.get(3).get(products.get(3).size() - 1));
if (flimit != limit) {
flimit = limit; //to stop using last element in fatching last products more than one time.
if (UtilityClass.isInternetAvailable(getApplicationContext())) {
new getProductsTask().execute(category);
} else {
Intent internet = new Intent(getBaseContext(), NointernetConnection.class);
startActivity(internet);
finish();
}
} else {
Log.d("FLimit", ">>" + "END");
}
} else {
progressDialog.dismiss();
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
});
}
}
First, you don't need to create a new object of your adapter class (productAdapter) every time in onPostExecute method and set adapter to gridview every time when data change or new response of your network call .This causes of scrolling gridview to top position.Instead you can create a setter method in your adapter class.
ArrayList <productDetails> productDetailsArr;
public void setProductDetailsArr(ArrayList<productDetails> productDetailsArr) {
this.productDetailsArr = productDetailsArr;
}
and in onPostExecute method write down the following code to check if adaper is null or not.If null then only you have to create a new instance.Otherwise you only have to provide a new dataset and just call notifyDataSetChanged().
if(productAdapter == null)
{
productAdapter = new productAdapter(category.this, productDetailsArr);
gridView.setAdapter(productAdapter);
}else{
productAdapter.setProductDetailsArr(productDetailsArr);
productAdapter.notifyDataSetChanged();
}

Android : change the background color of click on same button

I have one TextView in my application and want to change the Background color of the same TextView .When i click 1st time it would be red , click on same 2nd time it would be green and 3rd time click it would be blue color background by problematically.
textType = (TextView)findViewById(R.id.textRNG);
textType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Drawable d = textType.getBackground();
Log.e("textType "," click !!! ");
if(d.getConstantState() == getResources().getDrawable(R.drawable.red_circle_shape).getConstantState())
{
textType.setBackgroundResource(R.drawable.green_circle_shape);
}
if(d.getConstantState() == getResources().getDrawable(R.drawable.green_circle_shape).getConstantState())
{
textType.setBackgroundResource(R.drawable.blue_circle_shape);
}
if(d.getConstantState() == getResources().getDrawable(R.drawable.blue_circle_shape).getConstantState())
{
textType.setBackgroundResource(R.drawable.red_circle_shape);
}
}
});
This cod is not working.Thanks to appropriate.
Create a global variable x initialize it with 0. Then code like this:
textType = (TextView)findViewById(R.id.textRNG);
textType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(x<4)
{
x= x+1;
}
else{
x = 1;
}
if(x==1)
{
// red color
}
else if(x==2)
{
// blue color
}
else if(x==3)
{
// green color
}
}
});
Use the below code,
textType = (TextView)findViewById(R.id.textRNG);
textType.setOnClickListener(new View.OnClickListener() {
private int mCounter = 0;
#Override
public void onClick(View v)
{
if (mCounter == 0)
v.setBackgroundResource(R.drawable.red_circle_shape);
else
if (mCounter == 1)
v.setBackgroundResource(R.drawable.green_circle_shape);
else
v.setBackgroundResource(R.drawable.blue_circle_shape);
mCounter++;
}
});
Try this;
Define a global Variable int type.
Inside your onClick(), increment the int Variable
use switch or if statement to change the color when the variable increases e.g.
If(variable == 1)
// change color to Blue
else if (variable == 2)
// change color to Yellow
Hi Use the following code to Change the Color. Paste these lines inside your textView Onclick. Variable count is a global variable.
if (count == 0)
txtView.setTextColor(colorcode1);
else if (count == 1)
txtView.setTextColor(colorcode2);
else
txtView.setTextColor(colorcode3);
count++;
if (count > 2)
count = 0;
Try below code
TextView textType = (TextView)findViewById(R.id.textRNG);
textType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(current)
{
case 1:
tv.setBackgroundColor(Color.parseColor("#00ff00"));
current = 2;
break;
case 2:
tv.setBackgroundColor(Color.parseColor("#0000ff"));
current = 3;
break;
case 3:
tv.setBackgroundColor(Color.parseColor("#ff0000"));
current = 1;
break;
default:
break;
}
}
});

deleting multiple items from listview

I am trying to delete several items from my listview but it just deletes one element(even though i select more than one). The listview implements android.R.layout.simple_list_item_multiple_choice which has delListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE). I have a button where in the onClick method i would first like to check if there are no items selected if so prompt the user with some message. Else if there are some items selected delete them. This is what i have so far:
public void onClick(View v) {
// TODO Auto-generated method stub
selectItems();
Intent intent = new Intent(); ...
}
selectItems function:
private boolean selectItem()
{
String message = "Please select an item!";
for (int i = 0; i < array.size(); i++)
{
if(array.valueAt(i))
{
String item = delListView.getAdapter().getItem(array.keyAt(i)).toString();
Log.i("my_app", item + " selected");
deleteAdapter.remove(item);
deleteAdapter.notifyDataSetChanged();
return false; //item found
}
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
return true; //no item found
}
Thank you for your help!
I have managed to solve my problem. My solution was:
private void deleteItems() {
// TODO Auto-generated method stub
for (int i = (array.size()) - 1; i >= 0; i--)
{
if(array.valueAt(i))
{
String selected = deleteAdapter.getItem(array.keyAt(i));
Log.i("my_app", selected + " will be selected");
deleteAdapter.remove(selectat);
}
}
Intent intent = new Intent();
intent.putStringArrayListExtra(BUNDLE_DELETE, deleteList);
setResult(REQUEST_CODE_DELETE_STRING, intent);
getInstance().finish();
}
private boolean selectItem()
{
String message = "Please select an item!";
for (int i = 0; i < array.size(); i++)
{
if(array.valueAt(i))
{
String item = delListView.getAdapter().getItem(array.keyAt(i)).toString();
Log.i("my_app", item + " selected");
deleteItems();
return false;
}
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
return true;
}
I made a separate method for selecting the items and deleting them. Then i simply called the delete method in the selectItem(). In the onClick method i called the selectItem() method.
Thank you all for your help! :)
Notifydata set changed after all your items have been removed from the data map.
1) In onClick() call ListView.getCheckedItemPositions() to get the positions of the selected items in the list or ListView. getCheckedItemIds() to get the Id's of the selected items.
2) Then delete them.
3) Then call notifyDataSetChanged() on the Adapter to cause the list to be refreshed.
try something like this:
see an example :(Portuguese Link) http://nglauber.blogspot.com.br/2013/07/listview-com-selecao-multipla-actionbar.html
private boolean selectItem() {
String item = delListView.getAdapter().getItem(array.keyAt(i)).toString();
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = checked.size()-1; i >= 0; i--) {
if (checked.valueAt(i)) {
String item = delListView.getAdapter().getItem(checked.valueAt(i)).toString();
deleteAdapter.remove(item);
}
}
deleteAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
return true; //no item found
}
Edited:
I first want to verify(when
pressing a button) if there are no items selected.
mButton.setOnClickListener( new OnClickListener() {
#Override
public void onClick( final View v ) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
if ( checked.size() == 0 ) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
} );

How to Handle two listviews in one activity?

In my application,im using two listviews and both are not showing simultaneously.But im using the same "custom adapter class".But it is showing different results while implementing pagination.Pagination works well in the first listview which loads initially.But when i click another listview to show the results,it is not working
My Problem: How to implement pagination in both of these listviews effectively?Is it better to use two different custom adapter class?
Here the sample code which i done for pagination------
btnNext.setVisibility(View.VISIBLE);
TotalPages = TotalPages + 1;
if (pagenum == 0) {
btnPrev.setVisibility(View.INVISIBLE);
pagenum = pagenum + 1;
}
else {
recentCracks = web.getAllRecentCrackUps(pagenum);
if (recentCracks != null) {
adapter = new DynamicListAdapter(KidsCrackMeUp.this, recentCracks);
lstRecentPosts.setAdapter(adapter);
}
txtPageCount.setText(String.valueOf(pagenum));
txtTotalPages.setText(String.valueOf(totalpagecount));
}
if (pagenum == 1) {
//btnPrev.setEnabled(false);
btnPrev.setVisibility(View.INVISIBLE);
}
}
});
//Button Previous Ends Here-----------
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
pagenum = pagenum + 1;
btnPrev.setVisibility(View.VISIBLE);
TotalPages = TotalPages - 1;
//btnPrev.setEnabled(true);
if (TotalPages == 0) {
btnNext.setEnabled(false);
pagenum = pagenum - 1;
}
else
{
recentCracks = web.getAllRecentCrackUps(pagenum);
if (recentCracks != null)
{
adapter = new DynamicListAdapter(KidsCrackMeUp.this, recentCracks);
lstRecentPosts.setAdapter(adapter);
}
txtPageCount.setText(String.valueOf(pagenum));
txtTotalPages.setText(String.valueOf(totalpagecount));
}
if (TotalPages == 1) {
**strong text**// btnNext.setEnabled(false);
btnNext.setVisibility(View.INVISIBLE);
}
}
});
//Button Next Ends Here----
}
else
{
btnNext.setVisibility(View.GONE);
}
// rel.setVisibility(View.VISIBLE);
lstRecentPosts.setAdapter(adapter);
Please elaborate your question.I didnt get anything from it.
if you are trying to display two separate lists of same type then i would suggest you to go with SeparatedListAdapter

Categories

Resources