Android ListView में रनटाइम आइटम जोड़ने/अपडेट करने का तरीका
यह उदाहरण दिखाता है कि ArrayAdapter और notifyDataSetChanged() का उपयोग करके ListView में नए आइटम डायनामिकली कैसे जोड़े जाएं।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project चुनें।
चरण 2: लेआउट फ़ाइल (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter an item here"
android:inputType="text" />
<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editText"
android:text="Add item" />
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btnAdd" />
</RelativeLayout>
चरण 3: MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
ListView listView;
ArrayList list = new ArrayList<>();
ArrayAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btnAdd);
listView = findViewById(R.id.listView);
editText = findViewById(R.id.editText);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
button.setOnClickListener(v -> {
String newItem = editText.getText().toString().trim();
if (!newItem.isEmpty()) {
list.add(newItem);
editText.setText("");
adapter.notifyDataSetChanged(); // UI अपडेट के लिए जरूरी
}
});
}
}
चरण 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
बेहतर विकल्प: RecyclerView + DiffUtil
बड़े डेटासेट या जटिल अपडेट (हटाना, मूव करना, अपडेट करना) के लिए RecyclerView के साथ ListAdapter और DiffUtil उपयोग करें। यह एनिमेशन के साथ कुशल अपडेट देता है:
// RecyclerView.Adapter में submitList(newList); // DiffUtil ऑटोमेटिकली अंतर निकालता है