Android:FrameLayout上textview随机位置的奇怪行为

时间:2013-11-13 00:06:42

标签: android textview position fragment android-framelayout

到目前为止,我已经创建了一个应用,在TextView内的FrameLayout中显示两个Fragment,我有一个按钮来更新这些TextView的文本} s和根据文本的位置。 现在,文本已正确更新并显示所需的位置,但它永远不会匹配我在函数末尾看到并获得的实际位置(见下文)。

这是功能:

public void randomTextPos(View v) {
    FrameLayout rootView = (FrameLayout) findViewById(R.id.fragm_root_layout);
    TextView child = null;
    Log.i("size", "size = " + rootView.getWidth() + " " + rootView.getHeight());

    position[0] = (int) map((float) (Math.random()), 0, 1, 0,
            rootView.getWidth());
    position[1] = (int) map((float) (Math.random()), 0, 1, 0,
            rootView.getHeight());

    Log.i("onClick", "TextView at pos " + position[0] + " "
            + position[1]);

    if (idChild == 0) { // choose the child textview
        child = (TextView) rootView.findViewById(R.id.first_text);
    } else {
        child = (TextView) rootView.findViewById(R.id.second_text);
    }

    String mystring = Float.toString(position[0]) + "\n"
            + Float.toString(position[1]);
    char[] mystringtochar = mystring.toCharArray();
    child.setText(mystringtochar, 0, mystringtochar.length);

    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
            child.getWidth(), child.getHeight());
    params.gravity = Gravity.CENTER;
    params.leftMargin = (int) position[0];
    params.topMargin = (int) position[1];
    child.setLayoutParams(params);
    child.invalidate(); 
    rootView.invalidate();

    String myactualposition = "Left = " + Integer.toString(child.getLeft())
            + " Top " + Integer.toString(child.getTop());
    Log.i("Position!!!", myactualposition);// here I see that the getLeft 
        doesn't match with position[0]

    idChild = idChild == 0 ? 1 : 0;
}

并且这是我用来映射Math.random()中的值的函数,这不应该是一个问题,因为我已经成功使用它了:

public static float map(float x, float in_min, float in_max, float out_min,
        float out_max) {
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

以及Fragment

的布局
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragm_root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/red" >

<TextView
    android:id="@+id/first_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="first text\n view" />

<TextView
    android:id="@+id/second_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="second text\n view" />

</FrameLayout>

在此先感谢,我确信这很简单,我看不到它。

0 个答案:

没有答案