Android_Slip5A

1. Create the layout file (res/layout/activity_main.xml):

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
    android:id="@+id/collegeNameTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="My College"
    android:textSize="20sp"
    android:textStyle="normal"
    android:layout_centerInParent="true" />

    <Button
    android:id="@+id/changeColorButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Change Color"
    android:layout_below="@id/collegeNameTextView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="16dp" />

    </RelativeLayout>

2. Create the MainActivity Java file:
    import android.graphics.Color;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    import androidx.appcompat.app.AppCompatActivity;

    import java.util.Random;

    public class MainActivity extends AppCompatActivity {

    private TextView collegeNameTextView;
    private Button changeColorButton;

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

    collegeNameTextView = findViewById(R.id.collegeNameTextView);
    changeColorButton = findViewById(R.id.changeColorButton);

    changeColorButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    // Change text color to a random color
    int randomColor = getRandomColor();
    collegeNameTextView.setTextColor(randomColor);

    // Change text size to a random size between 10sp and 30sp
    float randomSize = getRandomSize();
    collegeNameTextView.setTextSize(randomSize);

    // Change text style to bold or normal randomly
    boolean isBold = new Random().nextBoolean();
    collegeNameTextView.setTypeface(null, isBold ? Typeface.BOLD : Typeface.NORMAL);
    }
    });
    }

    private int getRandomColor() {
    Random random = new Random();
    return Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256));
    }

    private float getRandomSize() {
    // Random size between 10sp and 30sp
    return new Random().nextFloat() * 20 + 10;
    }
    }

No comments:

Post a Comment