यह उदाहरण दर्शाता है कि Android ListView पर लॉन्ग क्लिक (दबाकर रखना) इवेंट को कैसे हैंडल किया जाए।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में नया प्रोजेक्ट बनाएं।
चरण 2: लेआउट में ListView जोड़ें
res/layout/activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
चरण 3: MainActivity.java में लॉन्ग क्लिक लिसनर
src/MainActivity.java:
package app.com.sample;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
String[] mobileArray = {"Android", "IPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listView);
ArrayAdapter<> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mobileArray);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
Toast.makeText(getApplicationContext(), "Long clicked: " + mobileArray[pos], Toast.LENGTH_SHORT).show();
return true; // true का मतलब इवेंट कन्ज्यूम हो गया
}
});
}
}
चरण 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>
ऐप चलाएं
किसी आइटम पर देर तक दबाएं - टोस्ट संदेश दिखाई देगा।
