Skip to content

Instantly share code, notes, and snippets.

@Binary-Finery
Created July 15, 2017 13:32
Show Gist options
  • Save Binary-Finery/afb3988ce9564e1291331d0e9241d35b to your computer and use it in GitHub Desktop.
Save Binary-Finery/afb3988ce9564e1291331d0e9241d35b to your computer and use it in GitHub Desktop.
Popup menu example without inflating XML. Menu items are added dynamically
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void clickEvent(View v){
int id = v.getId();
if (id == R.id.tv1){
showPopup(v, "Male", "Female");
}
if (id == R.id.tv2){
showPopup(v, "Student", "Employed");
}
}
private void showPopup(View view, String s1, String s2){
PopupMenu popupMenu = new PopupMenu(this, view);
popupMenu.getMenu().add(s1);
popupMenu.getMenu().add(s2);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(),
"you clicked " + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
popupMenu.show();
}
}
@Sana14
Copy link

Sana14 commented Oct 19, 2017

Grt Work Dean

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment