1

我正在开发一个由水平滚动视图组成的应用程序,我想获得 Horizo​​ntalScrollView 的宽度。怎样才能做到这一点?它对我来说归零

在 XML 中有这样的。

<TextView
    android:layout_width="50dp"
    android:layout_height="10dp"
    android:background="#00ff00" />

<HorizontalScrollView
    android:id="@+id/horizontalScrollView1"
    android:layout_width="fill_parent"
    android:layout_height="100dp"
    android:background="#ff0000" >

    <TextView
        android:layout_width="50dp"
        android:layout_height="10dp"
        android:background="#00ff00" />
</HorizontalScrollView>

在 Java 中

public class TestApplication extends Activity{

    private HorizontalScrollView horizontalScrollView1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testscroll);

        horizontalScrollView1 = (HorizontalScrollView)findViewById(R.id.horizontalScrollView1);
        horizontalScrollView1.getRight();
        horizontalScrollView1.getWidth();

        System.out.println("horizontalScrollView1.getWidth();::>"+horizontalScrollView1.getWidth());
        System.out.println("horizontalScrollView1.getWidth();::1>"+horizontalScrollView1.getMeasuredWidth());
    }

我已经尝试过以下方法,任何人都可以帮助我。

谢谢尼基尔

4

4 回答 4

2

你可以这样做:

int width = 0;
ViewTreeObserver vto = horizontalScrollView1.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        width = horizontalScrollView1.getWidth();
    }
});

希望有所帮助:)

于 2012-08-04T12:40:29.103 回答
1

请尝试这样

Log.d("TAG","scrollbar width: " + scrollView.getChildAt(0).getWidth());
Log.d("TAG","scrollbar height: " + scrollView.getChildAt(0).getHeight());
于 2018-07-08T17:58:20.537 回答
0

Instead of getWidth() method try with getMeasuredWidth() it will help you i think

于 2012-08-04T12:53:01.733 回答
0

您可以在这种情况下实现:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);

    int width = horizontalScrollView1.getMeasuredWidth();
    int height = horizontalScrollView1.getMeasuredHeight();
    System.out.println("widrh::>"+width);
    System.out.println("height::>"+height);
}
于 2012-08-04T14:50:54.123 回答