I am creating a listView and a floating button in my application and I would like to have the effect of hiding and returning depending on the scroll state. When the ListView
is being Scrolled the button hides fine, but when the scrolling stops the button does not return to its initial position.
Any ideas?
My Code:
public class MainActivity extends ActionBarActivity {
private ImageButton btn;
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] items = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "item 6", "Item 7", "Item 8", "Item 9", "Item 10", "Item 11", "Item 12", "Item 13", "Item 14", "item 15"};
lv = (ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, items);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "You have selected " + items[position].toString(), Toast.LENGTH_SHORT).show();
}
});
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if(scrollState == SCROLL_STATE_TOUCH_SCROLL){
btn.animate().translationYBy(350);
}else{
btn.animate().cancel();
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
btn = (ImageButton)findViewById(R.id.add_button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Floating Button Pressed", Toast.LENGTH_SHORT).show();
}
});
}
}
Thanks in advance!!!
This prevents the button to launch at short flinges:
public void onScrollStateChanged(AbsListView view, int scrollState) {
int btn_initPosY=btn.getScrollY();
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
btn.animate().cancel();
btn.animate().translationYBy(150);
} else {
btn.animate().cancel();
btn.animate().translationY(btn_initPosY);
}
}