write an application to print the star pattern on the activity



In this application, we have used the text view to print the star pattern on the screen using for loop. The xml file is as follows:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pattern " />
<TextView
android:id="@+id/tvPattern"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView2"
android:layout_marginTop="46dp"
android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

In this xml file we have used the relative layout and two text views, 1st is used to display the message pattern and second is used to print the star pattern. The java file is as follows:

package com.example.printpattern;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView p;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

p = (TextView) findViewById(R.id.tvPattern);

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
p.append("* ");
}
p.append("\n");
}
}


@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;
}

}

In this java file we have used the following packages:

android

In this file we have declared the following variables:
android

Here we have declared the variable of p of type TextView. Now we have to register the control inside the onCreate() method as follows:
android

Here we have registered the control by id defined in the xml file. Here we have used for loop. Inside the inner loop; this loop will continue till the given condition do not false and inside inner loop we have used the append() method that is used to append the passed string as parameter with the text view or control which we are using. Here we are using text view, so the string is append to the text view.
Here is the output:

android