Viewpager setCurrentItem() doesn't update onPageSelected() - java

When I swipe between questions, it loads current page number correctly
BUT when I use next button, first click doesnt loads pagenumber ( I mean onPageSelected() doesnt work.) second and other clicks loads content but it loads 1 page previous.
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
mPager = (ViewPager)findViewById(R.id.pager);
QuestionPagerAdapter mAdapter = new QuestionPagerAdapter();
mPager.setAdapter(mAdapter);
OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
tv.setText( mPager.getCurrentItem()+"");
}
};
mPager.setOnPageChangeListener(pageChangeListener);
Question.next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(getItem(+1));
}
}
private int getItem(int i) {
int a = mPager.getCurrentItem();
i += a;
return i;
}
});

Why not just doing this in your listener:
mPager.setCurrentItem(mPager.getCurrentItem() + 1);

Related

Java - Recycleview viewholder.category_name.settext is not working

#Override
protected void populateViewHolder(CategoryViewHolder viewHolder, Category model, int i) {
viewHolder.category_name.setText(model.getName());
Picasso.with(getActivity())
.load(model.getImage())
.into(viewHolder.category_image);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
// FancyToast.makeText(getActivity(),String.format("%d|%s",adapter.getRef(position).getKey(),model.getName()),FancyToast.LENGTH_LONG,FancyToast.SUCCESS,true).show();
Intent startGame = new Intent(getActivity(),Start.class);
Common.categoryId = adapter.getRef(position).getKey();
startActivity(startGame);
}
});
}
};
I have Tried the below code but viewHolder.category_name.setText() is not working
Actually setText is working but model.getName() is not working

Trying to call method from MainActivity in Another Activity it is me leading to error

I have Recycler ListView which I show in MainActivity and the first item it is as selected, I have done to click for another items but the last stays clicked and when I try to take this recycler view to show me in next Activity it doesn't work.
The first item it is selected but I have a click method which when click an image makes as selected but when I click a new image this works but the first item stays as selected so continues for others images. I want only a image to be selected.
I don't want to write twice the same code.
Is it good if I have a class only for this method which I can use everytime I want.
The id of recycler view list it is the same on both xml's.
If you have any suggestion for my question please let me know.
This is the adapter for the RecyclerView.
public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.ViewHolder>{
private int selectedItem;
private ArrayList<Integer> mImages = new ArrayList<>();
private ArrayList<String> mSearchUrl = new ArrayList<>();
private Context mContext;
public ListViewAdapter(ArrayList<Integer> images, ArrayList<String> SearchUrl, Context context) {
mImages = images;
mContext = context;
mSearchUrl = SearchUrl;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.s_engine_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
selectedItem = 0;
if (selectedItem == i) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
}
Glide.with(mContext).load(mImages.get(i))
.into(viewHolder.image);
viewHolder.searchUrl.setText(mSearchUrl.get(i));
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
selectedItem = i;
}
});
}
#Override
public int getItemCount() {
return mImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView searchUrl;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.ivEngine);
searchUrl = itemView.findViewById(R.id.ivEngineText);
}
}
}
This is the method in MainActivity.class
public void intSearch() {
mImages.add(R.drawable.s_bing);
mSearchUrl.add("https://www.bing.com/search?q=");
mImages.add(R.drawable.s_google);
mSearchUrl.add("https://www.google.com/search?q=");
mImages.add(R.drawable.s_yahoo);
mSearchUrl.add("www.yahoo.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
initRecyclerView();
}
private void initRecyclerView() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.lvEngines);
recyclerView.setLayoutManager(layoutManager);
ListViewAdapter adapter = new ListViewAdapter(mImages, mSearchUrl, this);
recyclerView.setAdapter(adapter);
}
This is the button which takes to another activity.
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = searchPlugin.getText().toString();
Cursor data = mDatabaseHelper.getData();
AddHistory(newEntry);
getFragmentRefreshListener().onRefresh();
Intent intent = new Intent(MainActivity.this, ActivitySearchEngine.class);
intent.putExtra("name", newEntry);
intent.putExtra("test", mSearchUrl.get(0));
startActivityForResult(intent, 2);
}
});
This is the another activity
public class ActivitySearchEngine extends Activity implements
SwipeRefreshLayout.OnRefreshListener {
public ImageView mHome;
public EditText searchPlugin;
public WebView webView;
Button btnSearch;
public ImageButton clearSearch, exitButton;
public ImageView favIcon;
public ProgressBar loadIcon;
String text;
SwipeRefreshLayout refreshLayout;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
private String selectedSearchUrl;
RecyclerView mListView;
MainActivity mainActivity = new MainActivity();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
mHome = findViewById(R.id.imgBtnHome);
searchPlugin = findViewById(R.id.etSearch);
webView = findViewById(R.id.webView);
clearSearch = findViewById(R.id.btnClearSearch);
btnSearch = findViewById(R.id.btnSearch);
favIcon = findViewById(R.id.imgViewFavIcon);
loadIcon = findViewById(R.id.progressBarIcon);
exitButton = findViewById(R.id.imgBtnStopLoad);
refreshLayout = findViewById(R.id.refreshLayout);
mListView = findViewById(R.id.lvEngines);
refreshLayout.setOnRefreshListener(this);
mDatabaseHelper = new DatabaseHelper(this);
mainActivity.intSearch(); // Here it is the error
Activity.ActivitySearchEngine}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
Intent receivedIntent = getIntent();
selectedName = receivedIntent.getStringExtra("name");
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
selectedSearchUrl = receivedIntent.getStringExtra("test");
searchPlugin.setText(selectedName);
loadIcon.setVisibility(View.VISIBLE);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("www.bing.com/search?=" + selectedName);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
favIcon.setImageBitmap(icon);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loadIcon.setVisibility(View.VISIBLE);
favIcon.setVisibility(View.GONE);
}
public void onPageFinished(WebView view, String url) {
try {
if (loadIcon.getVisibility() == View.VISIBLE) {
loadIcon.setVisibility(View.GONE);
favIcon.setVisibility(View.VISIBLE);
btnSearch.setVisibility(View.GONE);
mHome.setVisibility(View.VISIBLE);
exitButton.setVisibility(View.GONE);
clearSearch.setVisibility(View.VISIBLE);
favIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onRefresh();
}
});
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
searchPlugin.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
processButtonByTextLength();
}
});
mHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchPlugin.setText(null);
finish();
}
});
clearSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchPlugin.setText("");
}
});
public void processButtonByTextLength() {
String inputText = searchPlugin.getText().toString();
if(inputText.length() > 0) {
btnSearch.setVisibility(View.VISIBLE);
mHome.setVisibility(View.GONE);
clearSearch.setVisibility(View.VISIBLE);
favIcon.setVisibility(View.VISIBLE);
loadIcon.setVisibility(View.GONE);
exitButton.setVisibility(View.GONE);
} else if(inputText.length() == 0) {
btnSearch.setVisibility(View.GONE);
mHome.setVisibility(View.VISIBLE);
clearSearch.setVisibility(View.GONE);
}
}
#Override
public void onRefresh() {
webView.reload();
refreshLayout.setRefreshing(false);
}
}
This is the photo with RecyclerView at MainActivity.class
Photo of another Activity

onPageListener Is Not Working

I need some help with setting up the position of the Fragments in order for it to work with the the onPageListener so I can set the visibility of certain views. As I am new, I am rather unsure on how to do this. Thank you for your time and effort.
MainActivity.java
public class MainActivity extends FragmentActivity {
ViewPager viewpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
drawerGrid = (GridView) findViewById(R.id.content);
viewpager = (ViewPager) findViewById(R.id.pager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(1);
viewpager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//need some help here//
if(position == 1) {
drawerGrid.setVisibility(View.VISIBLE);
} else {
drawerGrid.setVisibility(View.GONE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
Fragments.java
public class Fragments extends FragmentPagerAdapter {
public Fragments(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: //need some help here//
return new Fragment1();
case 1:
return new Fragment2();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
try this:
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) {
switch (position) {
case 0:
drawerGrid.setVisibility(View.GONE);
break;
case 1:
drawerGrid.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
});
use it like:
ViewPager.addOnPageChangeListener(pageChangeListener);
// do this in a runnable to make sure the viewPager's views are already instantiated before triggering the onPageSelected call
viewpager.post(new Runnable()
{
#Override
public void run()
{
pageChangeListener .onPageSelected(viewPager.getCurrentItem());
}
});

How to Use button with Page indicator activity in android

I use the one Fragment and use three images for page slider. When i use this code(Button visible on 3rd screen) then the indicator not shifted or run only images are sliced. So, how i use the button and indicator together.
public class MainActivity extends FragmentActivity {
TestFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
Button button = (Button) findViewById(R.id.nextbutton1);
CirclePageIndicator indicator = (CirclePageIndicator)findViewById(R.id.indicator);
mIndicator = indicator;
indicator.setViewPager(mPager);
float density = getResources().getDisplayMetrics().density;
indicator.setBackgroundColor(0xFFFFFFFF);
indicator.setRadius(7 * density);
indicator.setPageColor(0xFFFFFFFF);
indicator.setFillColor(0xFFE63F36);
indicator.setStrokeColor(0xFF000000);
indicator.setStrokeWidth((float) (0.5* density));
mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
Button button = (Button) findViewById(R.id.nextbutton1);
if(position==2) {
button.setVisibility(View.VISIBLE);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
Intent i=new Intent(MainActivity.this,Login.class);
startActivity(i);
}
});
} else {
button.setVisibility(View.GONE);
}
/* FragmentChangeListener listener = (FragmentChangeListener) //cast fragment at this position to FragmentChangeListener
listener.onCentered();*/
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
});
}

Radio Group as Circular Page Indicator

I am trying to use RadioGroup as a CircularPageIndicator. The problem is with the RadioGroup.OnCheckedChangeListener. It seems to call it self when onPageSelected is called. However I want it to work vice versa i.e. when I select a radioButton it should change a view based on the location of the Array index being provided. However it seems as if onCheckedChange is never called when I change a check on the radio button and so onCheckedChange never triggers.
public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener, OnPageChangeListener {
ViewPager mImagePager;
ImagePagerAdapter mPagerAdapter;
RadioGroup mPageIndicator;
boolean swipeChange = false;
int[] mRadioButtonIds = new int[] { R.id.radio0, R.id.radio1, R.id.radio2, R.id.radio3, R.id.radio4 };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initComponents();
mPageIndicator.setOnCheckedChangeListener(this);
mImagePager.setAdapter(mPagerAdapter);
mImagePager.setOnPageChangeListener(this);
}
/**
*
*/
private void initComponents() {
mPageIndicator = (RadioGroup) findViewById(R.id.radioGroup1);
mImagePager = (ViewPager) findViewById(R.id.imgPager);
mPagerAdapter = new ImagePagerAdapter();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int pSelectedPagePosition) {
swipeChange = true;
mPageIndicator.check(mRadioButtonIds[pSelectedPagePosition]);
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (!swipeChange) {
int itemPosition = Arrays.asList(mRadioButtonIds).indexOf(checkedId);
mImagePager.setCurrentItem(itemPosition, true);
swipeChange = false;
}
}
}
Note : I don't want to use any third party code/lib to create a custom Circular Page Indicator.
Can any one please point a mistake here. Is there a reason for the RadioGroup not to work?
I forgot to take a look at the documentation!
http://developer.android.com/guide/topics/ui/controls/radiobutton.html

Categories

Resources