I'm using this Slider.
This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDemoSlider = (SliderLayout)findViewById(R.id.slider);
HashMap<String,Integer> file_maps = new HashMap<String, Integer>();
file_maps.put("Hannibal",R.drawable.hannibal);
file_maps.put("Big Bang Theory",R.drawable.bigbang);
file_maps.put("House of Cards",R.drawable.house);
file_maps.put("Game of Thrones", R.drawable.game_of_thrones);
for(String name : file_maps.keySet()){
TextSliderView textSliderView = new TextSliderView(this);
// initialize a SliderLayout
textSliderView
.description(name)
.image(file_maps.get(name))
.setScaleType(BaseSliderView.ScaleType.Fit)
.setOnSliderClickListener(this);
//add your extra information
textSliderView.bundle(new Bundle());
textSliderView.getBundle()
.putString("extra",name);
mDemoSlider.addSlider(textSliderView);
}
mDemoSlider.setPresetTransformer(SliderLayout.Transformer.Accordion);
mDemoSlider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
mDemoSlider.setCustomAnimation(new DescriptionAnimation());
mDemoSlider.stopAutoCycle();
mDemoSlider.addOnPageChangeListener(this);
}
Is there any way to stop infinite loop on sliders. I read that I should add mDemoSlider.stopAutoCycle(); but this does not have any effect.
Sorry, but you can't. At least not with this lib.
I've looked into the code and I saw that this "infinite scrolling" is default behavior, and if you want to disabled it you have either to implement your own slider, or suggest and edit for the original author...
The "problem" is on those two methods of the SliderLayout.java class:
/**
* move to next slide.
*/
public void moveNextPosition(boolean smooth) {
if (getRealAdapter() == null)
throw new IllegalStateException("You did not set a slider adapter");
mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, smooth);
}
// ...
/**
* move to prev slide.
*/
public void movePrevPosition(boolean smooth) {
if (getRealAdapter() == null)
throw new IllegalStateException("You did not set a slider adapter");
mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1, smooth);
}
And the setCurrentItem is located inside the ViewPagerEx.java class, where you can see that this infinite scrolling is default behavior. (Look at the setCurrentItemInternal method).
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) {
if (mAdapter == null || mAdapter.getCount() <= 0) {
setScrollingCacheEnabled(false);
return;
}
if (!always && mCurItem == item && mItems.size() != 0) {
setScrollingCacheEnabled(false);
return;
}
if (item < 0) {
item = 0;
} else if (item >= mAdapter.getCount()) {
item = mAdapter.getCount() - 1;
}
final int pageLimit = mOffscreenPageLimit;
if (item > (mCurItem + pageLimit) || item < (mCurItem - pageLimit)) {
// We are doing a jump by more than one page. To avoid
// glitches, we want to keep all current pages in the view
// until the scroll ends.
for (int i=0; i<mItems.size(); i++) {
mItems.get(i).scrolling = true;
}
}
final boolean dispatchSelected = mCurItem != item;
if (mFirstLayout) {
// We don't have any idea how big we are yet and shouldn't have any pages either.
// Just set things up and let the pending layout handle things.
mCurItem = item;
triggerOnPageChangeEvent(item);
requestLayout();
} else {
populate(item);
scrollToItem(item, smoothScroll, velocity, dispatchSelected);
}
}
Related
I use following to use recyclerview-selection:
selectionTracker = new SelectionTracker.Builder<>("lazy-load-img-list-selection", this.recyclerView, new KeyProvider(1), new Lookup(), StorageStrategy.createLongStorage()).build();
I expect
selectionTracker.setOnSelectionEnter
selectionTracker.setOnSelectionExit
to toggle buttons "remove selection" "clear selection" visibility
how to do?
update:
I can detect selection status recycler adapter #onBindViewHolder, but it's not good way, when determine onSelectionExit, I must detect all items status each rendering each item
I find solution:
selectionTracker.addObserver(new SelectionTracker.SelectionObserver() {
#Override
public void onItemStateChanged(#NonNull Object key, boolean selected) {
super.onItemStateChanged(key, selected);
Selection selection = selectionTracker.getSelection();
if (selected && selection.size() == 1) {
if (onSelectionEnter != null) {
onSelectionEnter.run();
}
} else if (!selected && selection.size() == 0) {
if (onSelectionExit != null) {
onSelectionExit.run();
}
}
}
});
I am trying to make an app that lists all the predefined tasks a person has to do daily. To mark them I'm using checkboxes in vertical linearlayout. I'm using for loop to iterate through the layout. I want that if a checkbox is checked, an integer (total) is incremented by 1 and if it is unchecked then the integer remains same. Here is the method:
CheckBox checkBox151, checkBox152, checkBox153;
LinearLayout sundayLayout;
int total = 0;
int[] boxState = {2, 2, 2, 2, 2, 2, 2};
public int formIsValid(LinearLayout layout) {
boolean wasChecked = false;
for (int i = 0; i < layout.getChildCount(); i++) {
View v = layout.getChildAt(i);
if (v instanceof CheckBox) {
if (((CheckBox) v).isChecked() && boxState[i] == 2 && wasChecked == false) {
total++;
boxState[i] = 0;
wasChecked = true;
} else if (boxState[i] == 1 && wasChecked == true) {
total = total - 1;
boxState[i] = 2;
} else if (boxState[i] == 0 && wasChecked == false) {
boxState[i] = 2;
}
}
}
return total;
}
I tried various logic statements, but what I get eventually is either the number getting incremented ok but decremented when I check the box again (I want it to decrement when unchecked, and increment when checked ONLY), but when I try this the app crashes due to bad logic statements.
Instant help needed, And thanks in advance...
This is the main purpose of Listeners. They watch the changes you make on components.
In your case you should use a CompoundButton.OnCheckedChangeListener
In your case, using a listener would let you only track the relevant changes (check / uncheck). Since it would be only called when a check / uncheck event has been triggered.
You also don't need to "validate" the values of the checkboxes by looping every time on the LinearLayout to be able to increment / decrement the counter value.
Here's how you would use it in your case:
public class MyActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private int counter;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
// ........
CheckBox checkBox1 = findViewById (R.id.checkbox1);
CheckBox checkBox2 = findViewById (R.id.checkbox2);
CheckBox checkBox3 = findViewById (R.id.checkbox3);
checkBox1.setOnCheckedChangeListener (this);
checkBox2.setOnCheckedChangeListener (this);
checkBox3.setOnCheckedChangeListener (this);
}
#Override
public void onCheckedChanged (CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
counter ++;
} else {
counter --;
}
}
}
Then when submitting your form, just grab the counter variable and do whatever you want with it.
EDIT: Regarding the 175 requirements, the concept stays the same. You'll register a listener to all of them.
The OnCreate method becomes:
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
// ........
// For each one of the 7 layouts you'll call the following (better create a method containing the below)
for (int i = 0; i < layout.getChildCount(); i++) {
View v = layout.getChildAt(i);
if (v instanceof CheckBox) {
((CheckBox)v).setOnCheckedChangeListener (this);
}
}
I have three checkboxes and if any two of them are selected I want to disable the third checkbox immediately. I am not getting how to proceed.
Manage your CheckBoxes in a List, so you can iterate over them.
List<CheckBox> boxes = new ArrayList<>();
Assign them like so (in onCreate() of your activity)
boxes.add((CheckBox) findViewById(R.id.checkbox1));
boxes.add((CheckBox) findViewById(R.id.checkbox2));
boxes.add((CheckBox) findViewById(R.id.checkbox3));
Add an onCheckedChangeListener like this:
for(CheckBox box : boxes){
box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
manageBoxes();
}
});
}
and finally your manageBoxes()
private void manageBoxes(){
int count = 0;
for(CheckBox box : boxes){
count += box.isChecked()?1:0;
}
if(count>=2){
for(CheckBox box : boxes){
box.setEnabled(box.isChecked());
box.setClickable(box.isChecked()); // not sure if needed
}
}else{
// reset all boxes
for(CheckBox box : boxes){
box.setEnabled(true);
box.setClickable(true);
}
}
}
Just a quick and dirty thought. Hope this works.
Plus: This is scalable, so you could include some more checkboxes if needed.
Try to implement this way :
private ArrayList<Integer> integers = null;
integers = new ArrayList<>();
chkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
int position = (int) yourview.getTag();
if (chkBox.isChecked()) {
integers.add(position);
chkBox.setChecked(true);
} else {
if (integers.size() > 0) {
for (int i=0; i<integers.size(); i++) {
if (integers.get(i) == position) {
integers.remove(i);
}
}
});
if (integers.size() > 2) {
//Disable your third checkbox
}
Add a change handler or a click handler on each of the checkboxes and let it call a small method that is responsible for checking the value of each checkbox: if two of them are true disable the third one.
For example:
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
handleCheckBoxes();
}
});
//Do this for all the checkboxes
private void handleCheckBoxes(){
int checkedCount = 0;
CheckBox uncheckedBox = null;
if(checkBox1.isChecked()){
checkedCount++;
}
else{
uncheckedBox = checkBox1;
}
if(checkBox2.isChecked()){
checkedCount++;
}
else{
uncheckedBox = checkBox2;
}
if(checkBox3.isChecked()){
checkedCount++;
}
else{
uncheckedBox = checkBox3;
}
if(checkedCount == 2){
uncheckedBox .setEnabled(false);
}
else{
//enable all checkboxes
checkBox1.setEnables(true);
checkBox2.setEnables(true);
checkBox3.setEnables(true);
}
In pseudo code this would be:
Create variable to hold the number of checkboxes checked, let's call it amountChecked
When a checkbox gets checked => increment the amountChecked
When a checkbox gets checked => check if the amountChecked is equal or greater than the allowedAmountChecked (in your case this is 2)
=> if it is greater or equal to the allowedAmountChecked then disable the remaining checkboxes
I'm trying to figure out exactly how to implement Google Play Game services in my app. On the Google Play Developer Console I've linked the game the relevant app using the SHA1 key and I know how to add leaderboards and achievements on here. I have also installed the Google Play services and Google Repository to Android Studio and added the dependency into build.gradle (as explained here: http://developer.android.com/google/play-services/setup.html) but I wasn't sure how to do the last 2 steps on that page (creating a Proguard exception and ensuring devices have the Google Play services APK) and if they are necessary - the latter of which even the Google Play Games sample projects don't seem to do.
Moreover, I'm not sure what code I actually need to put in my project to enable leaderboards and achievements, since according to this guide: https://developers.google.com/games/services/android/achievements, I use this code:
Games.Achievements.unlock(mGoogleApiClient, "my_achievement_id");
to unlock an achievement, for example, but there are no instructions on how I set up mGoogleApiClient. I've looked at the sample projects but it's still not clear what I'm supposed to do. Am I meant to copy and paste all of the code into my project? Are there certain sections I'm supposed to copy and paste? Do I have to write my own code for signing in to Google Play Games?
You should use getApiClient() instead of mGoogleApiClient.
Assuming you have an activity with a layout containing four buttons:
Leaderboard button - To launch the leaderboards,
Achievement button - To launch achievements
Sign in and Sign out buttons
For leaderboard, we push scores for best minutes, best distance covered and an overall highscore.
And for achievements, we unlock four achievements - survivor, warrior, lord, pride based on certain conditions.
Here's how you'd go about it:
public class GMSActivity extends BaseGameActivity implements OnClickListener{
Button lead;
Button achv;
final int RC_RESOLVE = 5000, RC_UNUSED = 5001;
//your game score. so we can push to cloud
int hS = 0;
//flags for achievements
boolean survivor;
boolean tribalWarriror;
boolean akonfemLord;
boolean zuluPride;
LinearLayout signInBar;
LinearLayout signOutBar;
Resources r;
private float bestTimeInSeconds;
private int bestTimeInMinutes;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.gms_layout);
r = getResources();
lead = (Button)findViewById(R.id.leaderboards);
achv = (Button)findViewById(R.id.achievements);
hS = loadScores();
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
lead.setOnClickListener(this);
achv.setOnClickListener(this);
signInBar = (LinearLayout)findViewById(R.id.sign_in_bar);
signOutBar = (LinearLayout)findViewById(R.id.sign_out_bar);
checkForAchievements();
if (isSignedIn()) {
onSignInSucceeded();
}else{
onSignInFailed();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == lead){
if (isSignedIn()) {
startActivityForResult(Games.Leaderboards.getAllLeaderboardsIntent(getApiClient()), RC_UNUSED);
} else {
showAlert(getString(R.string.leaderboards_not_available));
}
}else if(v ==achv){
if (isSignedIn()) {
startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()), RC_UNUSED);
} else {
showAlert(getString(R.string.achievements_not_available));
}
}else if(v.getId() == R.id.sign_in_button){
beginUserInitiatedSignIn();
}else if(v.getId() == R.id.sign_out_button){
signOut();
hello.setText(getString(R.string.signed_out_greeting));
signInBar.setVisibility(View.VISIBLE);
signOutBar.setVisibility(View.GONE);
}
#Override
public void onSignInFailed() {
hello.setText(getString(R.string.signed_out_greeting));
signInBar.setVisibility(View.VISIBLE);
signOutBar.setVisibility(View.GONE);
}
#Override
public void onSignInSucceeded() {
signInBar.setVisibility(View.GONE);
signOutBar.setVisibility(View.VISIBLE);
// Set the greeting appropriately on main menu
Player p = Games.Players.getCurrentPlayer(getApiClient());
String displayName;
if (p == null) {
// Log.w(TAG, "mGamesClient.getCurrentPlayer() is NULL!");
displayName = "";
} else {
displayName = p.getDisplayName();
}
// hello.setText("Hello, " + displayName);
pushAccomplishments();
Toast.makeText(this, getString(R.string.your_progress_will_be_uploaded),
Toast.LENGTH_LONG).show();
}
//check for achievements and unlock the appropriate ones
void checkForAchievements() {
// Check if each condition is met; if so, unlock the corresponding
// achievement.
bestTimeInSeconds = loadGameBestTimeSec();
if(bestTimeInSeconds >= 900){ //15 minutes
survivor = true;
tribalWarriror = true;
}
}
void pushAccomplishments() {
if (survivor)
Games.Achievements.unlock(getApiClient(), getString(R.string.achievement_survivor));
if (tribalWarriror)
Games.Achievements.unlock(getApiClient(), getString(R.string.achievement_tribal_warrior));
if(bestTimeInSeconds >= 60){ //1 minute atleast
bestTimeInMinutes = (int)bestTimeInSeconds/60;
Games.Leaderboards.submitScore(getApiClient(), getString(R.string.leaderboard_best_time_minutes), bestTimeInMinutes);
}
if(bestTimeInSeconds >= 10){ // 1 meter atleast
int bestDistance = (int)bestTimeInSeconds/10;
Games.Leaderboards.submitScore(getApiClient(), getString(R.string.leaderboard_best_distance_meters), bestDistance);
}
Games.Leaderboards.submitScore(getApiClient(), getString(R.string.leaderboard_top_score_points), hS);
}
#Override
//loading scores and achievements
private int loadScores() {
// TODO Auto-generated method stub
int score = 0;
try{
preferences = new SecurePreferences(getApplicationContext(),
"besiPreferences", "1234", true);
score = Integer.parseInt(preferences.getString("highScore"));
}catch(Exception e){}
return score;
}
private float loadGameBestTimeSec() {
float time = 0;
try{
preferences = new SecurePreferences(getApplicationContext(),
"besiPreferences", "1234", true);
time = Float.parseFloat(preferences.getString("gameTimeSec"));
}catch(Exception e){}
return time;
}
private int loadCalabashesCompleted() {
try{
preferences = new SecurePreferences(getApplicationContext(),
"makolaPref", "1234", true);
return Integer.parseInt(preferences.getString("bookCompleted")== null ? "0" : preferences.getString("bookCompleted"));
}catch(Exception e){
return 0;
}
}
private int loadLevelCompleted() {
try{
preferences = new SecurePreferences(getApplicationContext(),
"makolaPref", "1234", true);
return Integer.parseInt(preferences.getString("levelCompleted")== null ? "0" : preferences.getString("levelCompleted"));
}catch(Exception e){
return 0;
}
}
}
I need to implement few gestures in activity. I used Genymotion for that, saved gestures file in res/raw folder and wrote a code which is showing all good but keeps crashing the application. Does anyone know what could be the possible reason? I really tried to solve, but it seems i am missing something!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GestureOverlayView gesturesView = new GestureOverlayView(this);
View inflate = getLayoutInflater().inflate(R.layout.activity_garden,
null);
gesturesView.addView(inflate);
gesturesView.addOnGesturePerformedListener(this);
gestures = GestureLibraries.fromRawResource(this, R.raw.gestures);
if (!gestures.load()) {
finish();
}
setContentView(gesturesView);
}
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
ArrayList<Prediction> predictions = gestures.recognize(gesture);
int index = 0;
double maxScore = predictions.get(index).score;
for (int i = 1; i < predictions.size(); i++) {
if (predictions.get(i).score > maxScore) {
index = i;
maxScore = predictions.get(i).score;
}
}
Prediction p = predictions.get(index);
if (p.name.equalsIgnoreCase("Love"))
daisy.setImageResource(sp.getInt("Love", 0));
if (p.name.equalsIgnoreCase("Hit"))
daisy.setImageResource(sp.getInt("Hit", 0));
if (p.name.equalsIgnoreCase("Pet"))
daisy.setImageResource(sp.getInt("Pet", 0));
Toast.makeText(this, p.name + "\n" + p.score, Toast.LENGTH_SHORT)
.show();
}
On your code, what happen if you don't get any prediction?
Well, index will be equals to 0, and predictions.get(index) will crash because there is no object at index 0.
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
ArrayList<Prediction> predictions = gestures.recognize(gesture);
if (predictions == null || predictions.isEmpty()) {
return;
}
// continue the regular flow
}