Step 1: Open empty project on android studio.
Step 2: Open activity_main.xml and code as
<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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" tools:context=".MainActivity"> <TextView android:id="@+id/counterTxt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="40dp" android:textSize="120sp" android:text="25"/> <LinearLayout android:layout_below="@+id/counterTxt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:orientation="horizontal" android:layout_marginTop="80dp"> <Button android:id="@+id/minusBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="-" android:textSize="50sp"/> <Button android:id="@+id/resetBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Reset" android:textSize="50sp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp"/> <Button android:id="@+id/plusBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+" android:textSize="50sp"/> </LinearLayout> </RelativeLayout>
Step 3: Open MainActivity.java and code as
package com.example.taasbi_digitalcounter; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView counterTxt; private Button minusBtn; private Button plusBtn; private Button resetBtn; private int counter; private View.OnClickListener clickListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()){ case R.id.minusBtn : minusCounter(); break; case R.id.plusBtn : plusCounter(); break; case R.id.resetBtn : initCounter(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); counterTxt = (TextView) findViewById(R.id.counterTxt); minusBtn = (Button) findViewById(R.id.minusBtn); minusBtn.setOnClickListener(clickListener); plusBtn = (Button) findViewById(R.id.plusBtn); plusBtn.setOnClickListener(clickListener); resetBtn = (Button) findViewById(R.id.resetBtn); resetBtn.setOnClickListener(clickListener); initCounter(); } private void initCounter(){ counter = 0; counterTxt.setText(counter + ""); } private void plusCounter(){ counter++; counterTxt.setText(counter + ""); } private void minusCounter(){ counter--; counterTxt.setText(counter + ""); } }
0 comments:
Post a Comment