I'm developing a game Android app and I have a HorizontalScrollView
that is being populated with ImageViews
. Each ImageView
is clickable to select the level you want to play. I'm using a SavedPreference
to keep track of the last played level, and using that to determine which image is on screen when you load the menu. That way, if you're on level 30, you don't have to scroll all the way from level 1 every time.
I'm using a requestFocus()
to bring that ImageView
onto the screen, and it works fine, except for two relatively minor (but annoying) issues.
Here is what I'm doing in my for loop that populates the { HorizontalScrollView`:
final ImageView iv = new ImageView(LevelSelect.this);
iv.setImageResource(levelImages[i]);
iv.setFocusable(true);
iv.setFocusableInTouchMode(true);
iv.setId(i);
LinearLayout ll= (LinearLayout)findViewById(R.id.levelSelectGallery);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(300, LinearLayout.LayoutParams.MATCH_PARENT);
and I make it clickable:
String str = getString(R.string.level) + i + getString(R.string.avail);
if (storage.getBoolean(str,false)) { //check if level is available (unlocked)
iv.setClickable(true);
final int finalI = i;
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editor.putInt(getString(R.string.Current_Level_savepreferences), finalI); //set current level to clicked image
Intent intent = new Intent(LevelSelect.this, LevelStart.class);
LevelSelect.this.startActivity(intent); // begin LevelStart activity
}
});
} else {
iv.setImageResource(lockedImages[i]); // show locked image
}
and outside the loop, I set the focus:
//check if there is a saved level
focusLevel = storage.getInt(getString(R.string.Saved_Level), 5);
//set focus on saved level
findViewById(focusLevel).requestFocus();
This brings the focused item onto the screen, but just at the edge. I would prefer it to be centered if possible. I can live with that though. The main issue is that it seems that by setting the focus, it's now requiring two presses on the image to trigger the onClickListener
. I assume the first press is changing the focus and the second is clicking. If I remove the focus related code, it only requires one press.
Is there a better way to scroll the view to the desired image, or something different I should be doing with the focusing?