android代码创建布局

来源:互联网 发布:菊水 清酒 知乎 编辑:程序博客网 时间:2024/06/08 14:00

效果图:

这里写图片描述

布局代码:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout android:id="@+id/ll_view"              xmlns:android="http://schemas.android.com/apk/res/android"              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:orientation="vertical"></RelativeLayout>

页面代码:

public class ViewActivity extends Activity {    private RelativeLayout mLayout;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_view);        mLayout = $(R.id.ll_view);        mLayout.setBackgroundColor(Color.GREEN);        //单独设置属性        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(mLayout.getLayoutParams());        lp.setMargins(0, 100, 0, 0);        mLayout.setLayoutParams(lp);        ImageView imageView = new ImageView(this);        imageView.setId(getResources().getInteger(R.integer.one));        imageView.setImageDrawable(getResources().getDrawable(R.drawable.smile));        imageView.setBackgroundColor(Color.MAGENTA);        imageView.setPadding(20, 20, 20, 20);        mLayout.addView(imageView);        TextView textView = new TextView(this);        textView.setId(getResources().getInteger(R.integer.two));        textView.setBackgroundColor(Color.LTGRAY);        textView.setPadding(20, 0, 20, 20);        textView.setText("藏友号:54402");        textView.setTextSize(16);        //设置布局属性        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);        params.addRule(RelativeLayout.ALIGN_TOP, getResources().getInteger(R.integer.one));        params.addRule(RelativeLayout.RIGHT_OF, getResources().getInteger(R.integer.one));        mLayout.addView(textView, params);        Button button = new Button(this);        button.setId(getResources().getInteger(R.integer.three));        button.setBackgroundColor(Color.CYAN);        button.setPadding(20, 0, 20, 0);        button.setText("+ 关注");        button.setTextSize(16);        //设置布局属性        RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);        params1.addRule(RelativeLayout.BELOW, getResources().getInteger(R.integer.two));        params1.addRule(RelativeLayout.RIGHT_OF, getResources().getInteger(R.integer.one));        params1.addRule(RelativeLayout.ALIGN_BOTTOM, getResources().getInteger(R.integer.one));        mLayout.addView(button, params1);    }    public <T> T $(int viewID) {        return (T) findViewById(viewID);    }}
0 0