Scroll to certain position on application Android example code

ScrollTo(), getTop(), getBottom(), getLeft(), getRight(), ScrollView, LinearLayout Android Java xml example.
How get position of a View.
MainClass.java

/*
public void scrollTo (int x, int y) 
Since: API Level 1 
Set the scrolled position of your view. This will cause a call to onScrollChanged(int, int, int, int) and the view will be invalidated. 
 
This version also clamps the scrolling to the bounds of our child.
 
Parameters
x  the x position to scroll to 
y  the y position to scroll to  
  */
 
// sroll to top of hscrollViewMain
ScrollView hscrollViewMain = (ScrollView)findViewById(R.id.scrollViewMain);
hscrollViewMain.scrollTo(0, 0); // scroll to application top
 
// get position of a View
EditText hEdit = (EditText)findViewById(R.id.username_edit);
int nY_Pos = hEdit.getTop(); // getBottom(); X_pos  getLeft(); getRight();
// scroll to top of hEdit
hscrollViewMain.scrollTo(0,nY_Pos);

main.xml

 
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ScrollView
        android:id="@*id/scrollViewMain"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1">
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical"
            android:paddingTop="5dip"
            android:paddingBottom="13dip"
            android:paddingLeft="20dip"
            android:paddingRight="20dip">
            <TextView
                android:id="@+id/message"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dip" />
            <TextView
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textStyle="bold"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/login_activity_username_label" />
            <EditText
                android:id="@+id/username_edit"
                android:singleLine="true"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:minWidth="250dip"
                android:scrollHorizontally="true"
                android:capitalize="none"
                android:autoText="false"
                android:inputType="textEmailAddress" />
        </LinearLayout>
    </ScrollView>
 
</LinearLayout>
This entry was posted in Android Examples Code and tagged , , , , , , , . Bookmark the permalink.


Comments are closed.

23,473 views