2013年7月8日 星期一

【Android Note】動態新增元件到 Activity 上

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
     
        mainLinearLayout = new LinearLayout(this);
        mainLinearLayout.setOrientation(LinearLayout.VERTICAL);
        mainLinearLayout.setPadding(16, 16, 16, 16);
     
        toEditText = new EditText(this);
        toEditText.setHint("To");
     
        subjectEditText = new EditText(this);
        subjectEditText.setHint("Subject");
     
        messageEditText = new EditText(this);
        messageEditText.setHint("Message");
        messageEditText.setGravity(Gravity.TOP);
     
        sendButton = new Button(this);
        sendButton.setText("Send");
     
        mainLinearLayout.addView(toEditText);
        mainLinearLayout.addView(subjectEditText);
        mainLinearLayout.addView(messageEditText);
        mainLinearLayout.addView(sendButton);
     
        LinearLayout.LayoutParams messageParam =
        (LayoutParams) messageEditText.getLayoutParams();
        messageParam.weight=1;
        messageEditText.setLayoutParams(messageParam);
     
        LinearLayout.LayoutParams buttonParam =
        (LayoutParams) sendButton.getLayoutParams();
        buttonParam.gravity = Gravity.RIGHT;
        buttonParam.width=LayoutParams.WRAP_CONTENT;
        sendButton.setLayoutParams(buttonParam);
     
     
        setContentView(mainLinearLayout);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
}

沒有留言:

張貼留言