0

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

这是功能:

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>

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

4

0 回答 0