यह उदाहरण दर्शाता है कि Android में कस्टम सर्कुलर बटन कैसे बनाया जाए।
कस्टम सर्कुलर बटन बनाने का उदाहरण
चरण 1 - नया प्रोजेक्ट बनाएं
Android Studio में एक नया प्रोजेक्ट बनाएं: File → New Project पर जाएं और आवश्यक विवरण भरें।
चरण 2 - लेआउट XML में कोड जोड़ें
res/layout/activity_main.xml में निम्नलिखित कोड जोड़ें:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/parent"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/text"
android:textSize="18sp"
android:textAlignment="center"
android:background="@drawable/round_button"
android:layout_width="150dp"
android:textColor="#000"
android:layout_height="150dp" />
</LinearLayout>
उपरोक्त कोड में, हमने round_button बैकग्राउंड के साथ बटन लिया है। इसलिए drawable फोल्डर में round_button.xml बनाएं और निम्नलिखित कोड जोड़ें।
चरण 3 - Drawable XML बनाएं
res/drawable/round_button.xml में निम्नलिखित कोड जोड़ें:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
<shape android:shape="oval">
<solid android:color="#ffff00"/>
</shape>
</item>
<item android:state_pressed="true">
<shape android:shape="oval">
<solid android:color="#fff000"/>
</shape>
</item>
</selector>
उपरोक्त कोड में, हमने दो स्टेट लिए हैं: बटन दबाने पर और छोड़ने पर। जब उपयोगकर्ता बटन पर क्लिक करता है, तो यह बटन की स्टेट लेता है और बटन के लिए आकार प्रदान करता है।
चरण 4 - MainActivity.java में कोड जोड़ें
src/MainActivity.java में निम्नलिखित कोड जोड़ें:
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.text);
button.setText("Button");
}
}
ऐप चलाएं
अपने Android डिवाइस को कंप्यूटर से कनेक्ट करें और ऐप चलाएं। बटन पर क्लिक करने पर बटन का रंग बदलेगा।