在Android中的特定位置动态放置布局内的视图

时间:2013-10-25 05:09:30

标签: android android-layout

我试图在android中创建一个对话框窗口,我动态创建布局并将视图添加到其中...但我想将我的视图添加到布局中的特定位置..

这是我的代码段

    final Dialog dialog = new Dialog(this);
    FrameLayout fl=new FrameLayout(this);
    TextView et = new TextView(this);
    et.setText("asdas");

    fl.addView(et,100,1200);

    ColorDrawable cd=new ColorDrawable(android.graphics.Color.TRANSPARENT);
    dialog.getWindow().setBackgroundDrawable(cd);
    dialog.setContentView(fl);
这里有人可以帮助我

4 个答案:

答案 0 :(得分:2)

我用它在我的相对布局中的指定位置放置一个图像按钮。希望这会有所帮助:

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = (int)(marginLeft);
layoutParams.topMargin = (int)(marginTop);
imageButton.setLayoutParams(layoutParams);

修改

您可以为支持定位子视图的其他布局执行此操作。此方法甚至适用于较低的API版本。至少它适用于API 10.:)

答案 1 :(得分:0)

是的,你可以这样做......就像这样

   AdView ad = new AdView(this, AdSize.SMART_BANNER,  getString(R.string.admob_id));
        LinearLayout control_container =(LinearLayout)findViewById(R.id.ad_container);
        control_container.addView(ad);
        AdRequest adRequest = new AdRequest();
        ad.loadAd(adRequest);

并在您的xml文件中......

      <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#E9E5E6" >
    <LinearLayout
            android:id="@+id/ad_container"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:gravity="bottom"
            android:orientation="vertical" >
        </LinearLayout>


</RelativeLayout>

答案 2 :(得分:0)

假设您要在(200,200)位置添加TextView

试试这个......

    FrameLayout frameLayout = new FrameLayout(this);
    TextView textView = new TextView(this);
    textView.setTop(200);
    textView.setLeft(200);
    frameLayout.addView(textView, textViewWidth, textViewHeight);

答案 3 :(得分:0)

我认为这应该有用。

        Dialog dialog = new Dialog(this);
        FrameLayout frm_layout = new FrameLayout(this);
        android.widget.FrameLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                                                                          LayoutParams.WRAP_CONTENT);
        params.leftMargin = 100;
        params.topMargin = 1200;
        TextView et = new TextView(this);
        et.setText("asdas");
        frm_layout.addView(et, params);
        dialog.setContentView(frm_layout, new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
                                                           android.view.ViewGroup.LayoutParams.FILL_PARENT));