Create an application that will Demonstrate Button onClick() Event and change the TextView Color based on button Clicked
activity_main.xml
<LinearLayout
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:orientation="vertical"
tools:context=".MainActivity"
>
<TextView
android:layout_margin="10dp"
android:id="@+id/text_view"
android:text="A sample text view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25dp"
/>
<Button
android:id ="@+id/btnClickMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Click Me"
/>
</LinearLayout>
MainActivity.java
package com.example.helloworld;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.graphics.Color;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.btnClickMe);
TextView tv = (TextView) findViewById(R.id.text_view);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tv.setTextColor(Color.RED);
tv.setText("I'm Red Now...");
}
});
}
}
Output
After clicking on the button
0 Comments
Post a Comment