Home

Music

Video

Kanny

Android Studio Tutorial Context Menu (Simple Code)



MainActivity.Java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    ListView listViewContextMenu;
    String language[]={"Java","Kotlin","C++","COBOL","AppleScript","FoxPro","G-Code"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listViewContextMenu=(ListView)findViewById(R.id.listViewContextMenu);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,language);
listViewContextMenu.setAdapter(adapter);

// Register the ListView  for Context menu
registerForContextMenu(listViewContextMenu);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Select The Action");
menu.add(0, v.getId(), 0, "Code");//groupId, itemId, order, title
menu.add(0, v.getId(), 0, "Example");
menu.add(0, v.getId(), 0, "Tutorial");
}

@Override
public boolean onContextItemSelected(MenuItem item){
if(item.getTitle()=="Code"){
Toast.makeText(getApplicationContext(),"Selected Code",Toast.LENGTH_SHORT).show();
}
else if(item.getTitle()=="Example"){
Toast.makeText(getApplicationContext(),"Selected Example",Toast.LENGTH_SHORT).show();
} else if(item.getTitle()=="Tutorial") {
Toast.makeText(getApplicationContext(), "Selected Tutorial", Toast.LENGTH_SHORT).show();
}else{
return false;
}
return true;
}
 
}






activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:textColor="@color/Black"
android:textAlignment="center"
android:textSize="20dp"
android:text="Long press on any Language"/>
<ListView
android:id="@+id/listViewContextMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp" >
    </ListView>

</LinearLayout>





AndroidManifest.xml

<activity
android:name=".MainActivity"
android:label="MainActivity"
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

        </activity>

Share this



Fb tt wp ig
Powered by DuniyarHausa and Developed By DuniyarHausa Web team