Code Layout Example in Android Programming

0

This example shows how you can create your own layout through code instead of xml.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it CodeLayoutExample.

2.) Run for output.

Steps:

1.) Create a project named CodeLayoutExample and set the information as stated in the image.

Build Target: Android 4.0
Application Name: CodeLayoutExample
Package Name: com. example. CodeLayoutExample
Activity Name: CodeLayoutExample
Min SDK Version: 11

2.) Open CodeLayoutExample.java file and write following code there:

package com.example.codelayoutexample;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CodeLayoutExample extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LayoutParams params1 = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);

		TextView text = new TextView(this);
		text.setText("I am TextView");
		text.setLayoutParams(params1);
		EditText edit = new EditText(this);
		edit.setHint("This is EditView....");
		edit.setLayoutParams(params1);
		Button button = new Button(this);
		button.setText("Click me");
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast makeText = Toast.makeText(v.getContext(), "Clicked", Toast.LENGTH_SHORT);
				makeText.show();
			}
		});
		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);
		layout.setPadding(10, 10, 10, 10);
		layout.addView(text);
		layout.addView(edit);
		layout.addView(button);
		setContentView(layout);
	}
}

3.) Compile and build the project.

Output

Did you enjoy this article?
Share
the
Love
Get Free Updates
Proudly designed by Theme Junkie.