android LinearLayout.LayoutParams添加新视图

时间:2013-11-16 16:30:06

标签: android

我需要在我的LinearLayout中添加一个新按钮和textedit ..如果我创建一个新的参数,按钮会相互创建..

我的主要活动:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyTouchEventView tv = new MyTouchEventView(this);
        setContentView(tv);
        addContentView(tv.btnReset, tv.params);
        addContentView(tv.btnSave, tv.params2); 
    }

和MyTouchEventView:

public class MyTouchEventView extends View {

    public Button btnReset;
    public Button btnSave;
    public LinearLayout.LayoutParams params;
    public LinearLayout.LayoutParams params2;

    public MyTouchEventView(Context context) {
        super(context);

        btnReset = new Button(context);
        btnReset.setText("Vymazat platno");

        btnSave = new Button(context);
        btnSave.setText("Ulozit");


        params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        btnReset.setLayoutParams(params);

        params2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(40, 20, 40, 30);

        btnSave.setLayoutParams(params2);

http://i.stack.imgur.com/kvY1T.png

1 个答案:

答案 0 :(得分:0)

为什么不为您的活动创建简单的布局?

main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/my_edit_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="myText" />

    <Button
        android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="myText" />
</LinearLayout>

然后在onCreate方法中:

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);                   
}

另见http://developer.android.com/guide/topics/ui/layout/linear.html

相关问题