package com.example.layouts;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class HelloProgrammaticActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final EditText nameEditText = new EditText(this);
        final TextView helloTextView = new TextView(this);
        Button sayHelloButton = new Button(this);

        nameEditText.setId(1);
        helloTextView.setId(2);
        sayHelloButton.setId(3);

        Resources res = getResources();
        nameEditText.setHint(res.getString(R.string.helloHint));
        sayHelloButton.setText(res.getString(R.string.helloButton));

        RelativeLayout relativeLayout = new RelativeLayout(this);
        RelativeLayout.LayoutParams params;

        // EditText
        params = new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        relativeLayout.addView(nameEditText, params);

        // Button
        params = new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.BELOW, nameEditText.getId());
        relativeLayout.addView(sayHelloButton, params);

        // TextView
        params = new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.BELOW, sayHelloButton.getId());
        relativeLayout.addView(helloTextView, params);

        // Padding
        int vpad = getResources().getDimensionPixelOffset(
                R.dimen.activity_vertical_margin);
        int hpad = getResources().getDimensionPixelOffset(
                R.dimen.activity_horizontal_margin);
        relativeLayout.setPadding(hpad, vpad, hpad, vpad);
        
        params = new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        setContentView(relativeLayout, params);

        sayHelloButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String name = nameEditText.getText().toString();
                helloTextView.setText("Hello " + name + "!");
            }
        });
    }
}