在Android中的FrameLayout中放置视图

hpi*_*que 9 android android-layout android-framelayout

我想以编程方式在FrameLayout中添加一个视图,并将其放置在布局中具有特定宽度和高度的特定点.FrameLayout支持这个吗?如果没有,我应该使用中间ViewGroup来实现这一目标吗?

int x; // Can be negative?
int y; // Can be negative?
int width;
int height;
View v = new View(context);
// v.setLayoutParams(?); // What do I put here?
frameLayout.addView(v);
Run Code Online (Sandbox Code Playgroud)

我最初的想法是向FrameLayout添加一个AbsoluteLayout并将视图放在AbsoluteLayout中.不幸的是,我刚刚发现AbsoluteLayout已被弃用.

任何指针都将非常感激.谢谢.

tul*_*84z 12

以下示例(工作代码)显示了如何在FrameLayout中放置视图(EditText).此外,它还展示了如何使用FrameLayout的setPadding setter设置EditText的位置(每次用户点击FrameLayout时,EditText的位置都设置为点击的位置):

public class TextToolTestActivity extends Activity{
    FrameLayout frmLayout;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        frmLayout = (FrameLayout)findViewById(R.id.frameLayout1);
        frmLayout.setFocusable(true);
        EditText et = new EditText(this);

        frmLayout.addView(et,100,100);
        frmLayout.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.i("TESTING","touch x,y == " + event.getX() + "," +     event.getY() );
                frmLayout.setPadding(Math.round(event.getX()),Math.round(event.getY()) , 0, 0);
            return true;
        }
    });

}
Run Code Online (Sandbox Code Playgroud)

}

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <FrameLayout 
        android:id="@+id/frameLayout1" 
        android:layout_height="fill_parent" android:layout_width="fill_parent">
    </FrameLayout>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

  • 嗯..这是一个框架内部的视图不是吗?另外,我将展示如何使用setPadding setter将嵌入视图定位在特定位置. (2认同)

小智 2

确实,使用 FrameLayout,所有子项都固定在屏幕的左上角,但您仍然可以对设置其填充进行一些控制。如果为不同的子项设置不同的填充值,它们将显示在 FrameLayout 中的不同位置。

  • 但这样做的问题是,点击侦听器将从左上角开始跨越整个区域...... (9认同)