Site icon WebArtDeveloper

Basic Concept of ListView Control and How to Create Context Menu in Android

In this tutorial following is shown:

Hints:

Code:

activity_main.xml

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”.MainActivity” >

<ListView
android:id=”@+id/listView1″
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_alignParentTop=”true”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”43dp” >
</ListView>
</RelativeLayout>

 

MainActivity.java

package com.example.demo;

import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity{

ListView lv1;
String [] contacts={“John”,”Abby”,”David”,”Marie”,”Peter”};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv1=(ListView)findViewById(R.id.listView1);
ArrayAdapter <String> ad1=new ArrayAdapter <String> (this,android.R.layout.simple_list_item_1,contacts);
lv1.setAdapter(ad1);
registerForContextMenu(lv1);
}

@Override
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle(“Select the Action”);
menu.setHeaderIcon(R.drawable.ic_launcher);
menu.add(0,v.getId(),0,”Call”);
menu.add(0,v.getId(),0,”SMS”);
}

@Override
public boolean onContextItemSelected(MenuItem item)
{
if(item.getTitle()==”Call”)
{
Toast.makeText(getApplicationContext(), “Starting Call”, Toast.LENGTH_LONG).show();

}
else if(item.getTitle()==”SMS”)
{
Toast.makeText(getApplicationContext(), “Sending SMS”, Toast.LENGTH_LONG).show();

}
else
{
return false;
}
return true;
}
//public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
//return true;
}

https://youtu.be/NV-F67v0PKg

Exit mobile version