Reputation: 6962
I have a horizontal scroll bar that holds 12 buttons, I want to scroll to a specific button to be the middle of the screen,
Currently I am using
monthScrollView.smoothScrollBy((int) buttons.get(arrayNumber).getX(),0);
Which scrolls the button just off the screen, so how to I find the value of half the screen to subtract?
Upvotes: 0
Views: 1639
Reputation: 3584
Try
int[] loc = new int[2];
buttons.get(arrayNumber).getLocationInWindow(loc);
horizontalScrollView.scrollTo(loc[0], 0);
Example Code - activity_scroll.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black">
<HorizontalScrollView
android:id="@+id/horizon"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/button_1"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="1"
android:layout_margin="5dp" />
<Button
android:id="@+id/button_2"
android:layout_width="100dp"
android:text="2"
android:layout_height="100dp"
android:layout_margin="5dp" />
<Button
android:id="@+id/button_3"
android:layout_width="100dp"
android:text="3"
android:layout_height="100dp"
android:layout_margin="5dp" />
<Button
android:id="@+id/button_4"
android:layout_width="100dp"
android:text="4"
android:layout_height="100dp"
android:layout_margin="5dp" />
<Button
android:id="@+id/button_5"
android:layout_width="100dp"
android:text="5"
android:layout_height="100dp"
android:layout_margin="5dp" />
<Button
android:id="@+id/button_6"
android:text="6"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="5dp" />
<Button
android:id="@+id/button_7"
android:layout_width="100dp"
android:text="7"
android:layout_height="100dp"
android:layout_margin="5dp" />
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
TestActivity.java
public class TestActivity extends AppCompatActivity implements View.OnClickListener {
View[] views = new View[7];
int res[] = {R.id.button_1, R.id.button_2, R.id.button_3, R.id.button_4, R.id.button_5, R.id.button_6, R.id.button_7};
HorizontalScrollView horizontalScrollView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scroll);
for (int i = 0; i < res.length; i++) {
views[i] = findViewById(res[i]);
views[i].setOnClickListener(this);
}
horizontalScrollView = (HorizontalScrollView) findViewById(R.id.horizon);
}
@Override
public void onClick(View v) {
int[] loc = new int[2];
views[3].getLocationInWindow(loc);
horizontalScrollView.scrollTo(loc[0], 0);
}
}
My working example.
Upvotes: 1