xml布局和动态布局结合使用

1. 新建工程

2. 新建布局 userview.xml, 布局中上面部分是一个textview, 下部分是一个button

<?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"

    >

<TextView  

    android:layout_width="fill_parent" 

    android:layout_height="wrap_content" 

    android:text="@string/hello"

    />

    <Button  

    android:layout_width="fill_parent" 

    android:layout_height="wrap_content" 

    android:text="@string/hello"

    />

</LinearLayout>

3. 新建View--MyView, 首先加载了userview布局,然后横向部分新增加了一个button按钮

public class MyView extends LinearLayout {

private View userview;

private Button anotherButton;

public MyView(Context context, AttributeSet attrs) {

super(context);

// TODO Auto-generated constructor stub

setOrientation(LinearLayout.HORIZONTAL);

userview = inflate(context, R.layout.userview, null);//这里的第三个参数应该为null

anotherButton = new Button(context);

anotherButton.setText("another");

addView(userview);

addView(anotherButton);

}

}

4. MainActivity

public class MainActivity extends Activity {

private MyView myView;

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

    myView = new MyView(this, null);

    setContentView(myView);

    }

}

你可能感兴趣的:(xml,android,layout,button,Constructor,encoding)