Thursday, November 4, 2021

Click Button Show text or image in Android Studio | Learn Android Studio...

Xml Code:- 



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edt"/>

<TextView
android:id="@+id/txt"
android:textSize="30sp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Show"
android:id="@+id/btn"/>
</LinearLayout>


Java Code:-  




package com.niranjan.buttonclick;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
TextView textView;
Button button;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.txt);
editText=findViewById(R.id.edt);
button=findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = editText.getText().toString();
if (name.isEmpty()){
textView.setText("Hello Niranjan");
}else {
textView.setText(name);
}
}
});

}
}

No comments:

Post a Comment

Activity Navigation One Activity to another Activity

Main Activity :-   <? xml version ="1.0" encoding ="utf-8" ?> < RelativeLayout xmlns: android ="http://sch...