Playing a sound file through a menu item - android

I am trying to play a sound file through a menu item which exists in a fragment.
Here is the full code of my fragment,
public class OneFragment extends Fragment {
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_one, container,false);
ImageButton popupCTelevision = (ImageButton)rootview.findViewById(R.id.chineseTelevision);
ImageButton popupCBathe = (ImageButton)rootview.findViewById(R.id.chineseBathe);
ImageButton popupCSick = (ImageButton)rootview.findViewById(R.id.chineseSick);
popupCTelevision.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(getActivity().getApplicationContext(), v);
popupMenu.inflate(R.menu.menu_chinese_television);
popupMenu.show();
}
});
popupCBathe.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(getActivity().getApplicationContext(), v);
popupMenu.inflate(R.menu.menu_chinese_bathe);
popupMenu.show();
}
});
popupCSick.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(getActivity().getApplicationContext(), v);
popupMenu.inflate(R.menu.menu_chinese_sick);
popupMenu.show();
}
});
return rootview;
}
public boolean onMenuItemClick(MenuItem item){
switch(item.getItemId()) {
case R.id.c_bathe:
final MediaPlayer CSick = MediaPlayer.create(getActivity(), R.raw.c_bathe);
MenuItem playCSick = (MenuItem) getView().findViewById(R.id.c_sick);
CSick.start();
playCSick.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
CSick.start();
return true;
}
});
default:
return false;
}
}
}
I think the issue is that the method onMenuItemClick is not used at all. How do I implement this method for the code?
How do I do it similarly to pressing a button to play the sound file?
final MediaPlayer englishSoundMP = MediaPlayer.create(this, R.raw.english_bath);
Button playEnglishBath = (Button) this.findViewById(R.id.play_english);
playEnglishBath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
englishSoundMP.start();
}
});

Related

How to restore fragment states while using bottom navigation view in android?

I am trying to do restoring the fragment view state values(text view,..etc) when back from second fragment in android bottom navigation view.
MyActivity.java
public class LandingPage extends AppCompatActivity implements ProductFragment.AddToCart {
Fragment fragment;
TextView txtCart;
Button btnCart;
ItemData itemData;
ArrayList<ItemData> itemDataList;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
fragment = new ProductFragment();
loadFragment(fragment);
return true;
case R.id.nav_profile:
fragment = new ReportsFragment();
loadFragment(fragment);
return true;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing_page);
txtCart = findViewById(R.id.txt_cart);
btnCart = findViewById(R.id.btn_cartImg);
itemDataList = new ArrayList<>();
BottomNavigationView bottomNavigationView = findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
loadFragment(new ProductFragment());
}
private void loadFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
ProductFragment.java
public class ProductFragment extends Fragment {
private OnFragmentInteractionListener mListener;
Button btnCart1,btnCart2,btnCart3;
AddToCart addToCart;
TextView txtItem1Des,txtItem1Price,txtItem2Des,txtItem2Price,txtItem3Des,txtItem3Price;
Button btnCart1Inc,btnCart1Dec,btnCart2Inc,btnCart2Dec,btnCart3Inc,btnCart3Dec;
TextView cart1txt,cart2txt,cart3txt;
String itemDes,itemPrice,itemImg,itemCount;
int quantity1,quantity2,quantity3;
public ProductFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product, container, false);
btnCart1 = view.findViewById(R.id.cart1);
txtItem1Des = view.findViewById(R.id.cart1_desc);
txtItem1Price = view.findViewById(R.id.cart1_price);
btnCart1Inc = view.findViewById(R.id.cart1Inc);
btnCart1Dec = view.findViewById(R.id.cart1Dec);
cart1txt = view.findViewById(R.id.cart1txt);
btnCart2 = view.findViewById(R.id.cart2);
txtItem2Des = view.findViewById(R.id.cart2_desc);
txtItem2Price = view.findViewById(R.id.cart2_price);
btnCart2Inc = view.findViewById(R.id.cart2Inc);
btnCart2Dec = view.findViewById(R.id.cart2Dec);
cart2txt = view.findViewById(R.id.cart2txt);
btnCart3 = view.findViewById(R.id.cart3);
txtItem3Des = view.findViewById(R.id.cart3_desc);
txtItem3Price = view.findViewById(R.id.cart3_price);
btnCart3Inc = view.findViewById(R.id.cart3Inc);
btnCart3Dec = view.findViewById(R.id.cart3Dec);
cart3txt = view.findViewById(R.id.cart3txt);
quantity1 = Integer.parseInt(cart1txt.getText().toString());
quantity2 = Integer.parseInt(cart2txt.getText().toString());
quantity3 = Integer.parseInt(cart3txt.getText().toString());
buttonInitialization();
addingToCart();
return view;
}
private void addingToCart() {
btnCart1Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity1 <= 1){
btnCart1.setVisibility(View.VISIBLE);
btnCart1Dec.setVisibility(View.INVISIBLE);
btnCart1Inc.setVisibility(View.INVISIBLE);
cart1txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(1);
}else {
quantity1 = quantity1-1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
}
});
btnCart1Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity1 = quantity1+1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
});
btnCart2Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity2 <= 1){
btnCart2.setVisibility(View.VISIBLE);
btnCart2Dec.setVisibility(View.INVISIBLE);
btnCart2Inc.setVisibility(View.INVISIBLE);
cart2txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(2);
}else {
quantity2 = quantity2-1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
}
});
btnCart2Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity2 = quantity2+1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
});
btnCart3Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity3 <= 1){
btnCart3.setVisibility(View.VISIBLE);
btnCart3Dec.setVisibility(View.INVISIBLE);
btnCart3Inc.setVisibility(View.INVISIBLE);
cart3txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(3);
}else {
quantity3 = quantity3-1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
}
});
btnCart3Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity3 = quantity3+1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
});
}
private void buttonInitialization() {
btnCart1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem1Price.getText().toString().trim();
itemDes = txtItem1Des.getText().toString().trim();
itemCount = cart1txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"1");
btnCart1.setVisibility(View.INVISIBLE);
btnCart1Dec.setVisibility(View.VISIBLE);
btnCart1Inc.setVisibility(View.VISIBLE);
cart1txt.setVisibility(View.VISIBLE);
}
});
btnCart2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem2Price.getText().toString().trim();
itemDes = txtItem2Des.getText().toString().trim();
itemCount = cart2txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"2");
btnCart2.setVisibility(View.INVISIBLE);
btnCart2Dec.setVisibility(View.VISIBLE);
btnCart2Inc.setVisibility(View.VISIBLE);
cart2txt.setVisibility(View.VISIBLE);
}
});
btnCart3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem3Price.getText().toString().trim();
itemDes = txtItem3Des.getText().toString().trim();
itemCount = cart3txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"3");
btnCart3.setVisibility(View.INVISIBLE);
btnCart3Dec.setVisibility(View.VISIBLE);
btnCart3Inc.setVisibility(View.VISIBLE);
cart3txt.setVisibility(View.VISIBLE);
}
});
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
addToCart = (AddToCart) context;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public interface AddToCart{
void cartCount(String item_img,String item_price,String item_desc,String item_count,String item_pos);
void removeItemFromCart(int removeItem);
void itemCount(String itemCount,String position);
}
}
Here in ProductFragment iam going to add values to text view. When i was coming from ReportFragment the view values are going to be cleared in ProductFragment.
I would consider doing that in two steps:
save fragment instance instead of re-creating a new one every time
private ProductFragment productFragment;
private ReportsFragment reportsFragment;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
if(productFragment == null)
productFragment = new ProductFragment();
loadFragment(productFragment);
break;
case R.id.nav_profile:
if(reportsFragment == null)
reportsFragment = new ReportsFragment();
loadFragment(reportsFragment);
break;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
referring to this question/answer, you should implement in your fragment both void onSaveInstanceState(final Bundle outState) and void onActivityCreated(Bundle savedInstanceState)
In that way you will surely keep the instance of your fragment instead of creating a new one every time (new MyFragment() will always re-create it). In addition, saving your views state in onSaveInstanceState and restoring it in your onActivityCreate, will allow you to keep your views/values.
I wrote that by hand without a compiler, so it might not be perfect.
let me know if you need further information.
Good luck
I am using this solution and it works for me.
You should see my detailed answer to a similar question. I hope it will solve your problem.

How can I implement tabs in an Android Browser?

I am trying to implement tab functionality in an Android browser. I tried to save the webpage in a cache, but I can't figure out how to save multiple of them and load them when the user switches tabs. How could I implement this?
I would like to save the current webpage in a cache when the user wants to add a new tab and open Main_activity, and then next time when the user switches tabs, the current webpage should get saved in a cache, and the intended webpage of the intended tab gets loaded in the webview. Now the issue is, I don't know how to handle multiple webpages in a cache, and select which one to load when.
My code consists of two activities, main_activity with some icons and webView_activity with a simple webview. I am using a custom dialog box with a ListView in it, so I will need to add new rows for new tabs and edit them when tabs are switched.
Here is my main_activity
public class MainActivity extends AppCompatActivity {
ImageView yt,google,gm,twitter;
SearchView g_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
g_search = (SearchView) findViewById(R.id.g_search);
g_search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("query",query);
startActivity(i);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
yt = (ImageView) findViewById(R.id.yt);
google = (ImageView) findViewById(R.id.google);
gm = (ImageView) findViewById(R.id.gm);
twitter = (ImageView) findViewById(R.id.twitter);
yt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.youtube.com");
startActivity(i);
}
});
google.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.google.com");
startActivity(i);
}
});
gm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.gmail.com");
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.twitter.com");
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.m1, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("query",query);
startActivity(i);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_new_tab){
}
if(item.getItemId()==R.id.action_incognito_mode){
}
if(item.getItemId()==R.id.action_bookmarks){
}
if(item.getItemId()==R.id.action_history){
}
if(item.getItemId()==R.id.action_downloads){
}
if(item.getItemId()==R.id.action_settings){
Intent i = new Intent(MainActivity.this,SettingsActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_about){
Intent i = new Intent(MainActivity.this,about.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
Here is my web_view activity
public class webview1 extends AppCompatActivity {
CustomWebView web1;
String search_q,shortcut;
FloatingActionButton fab;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview1);
web1 = (CustomWebView) findViewById(R.id.web1);
web1.setGestureDetector(new GestureDetector(new CustomGestureDetector()));
web1.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(final WebView view, int errorCode, String description,
final String failingUrl) {
fragmentManager.beginTransaction()
.replace(R.id.container, new blankState())
.commit();
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
registerForContextMenu(web1);
// web1.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
web1.getSettings().setJavaScriptEnabled(true);
web1.getSettings().setBuiltInZoomControls(true);
web1.getSettings().setDisplayZoomControls(false);
web1.getSettings().setLoadWithOverviewMode(true);
web1.getSettings().setUseWideViewPort(true);
search_q=getIntent().getStringExtra("query");
shortcut=getIntent().getStringExtra("shortcut");
bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_toolbar);
ImageView action_back = (ImageView) findViewById(R.id.action_back);
action_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
bottomNavigationView.setVisibility(GONE);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// code for launching new tab here
}
});
web1.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view, int progress ){
frame_layout.setVisibility(View.VISIBLE);
progress_bar.setProgress(progress);
if(progress==100){
frame_layout.setVisibility(GONE);
srl.setRefreshing(false);
}
super.onProgressChanged(view, progress);
}
});
progress_bar.setProgress(0);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_url){
ShowUrlDialog();
return true;
}
if(item.getItemId()==R.id.action_home){
Intent i = new Intent(webview1.this,MainActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_new_tab){
// code to launch new tab here
}
if(item.getItemId()==R.id.action_incognito_mode){
}
if(item.getItemId()==R.id.action_bookmarks){
}
if(item.getItemId()==R.id.action_history){
}
if(item.getItemId()==R.id.action_downloads){
}
if(item.getItemId()==R.id.action_settings){
Intent i = new Intent(webview1.this,SettingsActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_about){
Intent i = new Intent(webview1.this,about.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.m2, menu);
// Associate searchable configuration with the SearchView
return true;
}
#Override
public void onBackPressed() {
if (web1.canGoBack()) {
web1.goBack();
} else {
super.onBackPressed();
}
}
}

Dialog Open on Recycler view Row button click

In Recycler View I click on a button add to cart a dialog is open.
In Recycler view adapter
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.addtocart.setOnClickListener((Mp3HindiLandingActivity) context);
}
In My Activity(Mp3HindiLandingActivity)
#Override
public void onClick(final View v) {
switch (v.getId()) { case R.id.addtocart:
PopupMenu popup = new PopupMenu(ctx, v);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
Toast.makeText(v.getContext(), "FriendRequest", Toast.LENGTH_LONG).show();
return true;
case R.id.menu2:
Toast.makeText(v.getContext(), "Block | Hide ", Toast.LENGTH_LONG).show();
return true;
default:
return false;
}
}
});
popup.getMenuInflater().inflate(R.menu.menu, popup.getMenu());
popup.show();
break;`
}}
It Shows the the menu below addtocart icon but I need the menu items having different background as per the image attached?
Please let me know how this will be implemented
you can try this.
paletteViewHolder.btncart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
PopupMenu popup = new PopupMenu(paletteViewHolder.imgpopup.getContext(), v);
// This activity implements OnMenuItemClickListener .
//popup.setOnMenuItemClickListener ((OnMenuItemClickListener) this);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.friendrequest:
Toast.makeText(v.getContext(), "FriendRequest", Toast.LENGTH_LONG).show();
return true;
case R.id.blockhide:
Toast.makeText(v.getContext(), "Block | Hide ", Toast.LENGTH_LONG).show();
return true;
case R.id.followunfollow:
Toast.makeText(v.getContext(), "Follow/UnFollow", Toast.LENGTH_LONG).show();
return true;
default:
return false;
}
//return false;
}
});
popup.inflate(R.menu.menu);
popup.show();
}
});
//create below menu.xml file on menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu1"
android:title="menu1"/>
<item
android:id="#+id/menu2"
android:title="menu2"/>
<item
android:id="#+id/menu3"
android:title="menu3"/>
</menu>
its helpfull for you.
First create an inner class ViewHolder likes below:
private class MyViewHolder extends RecyclerView.ViewHolder {
public Button btnCart;
public MyViewHolder(View view) {
super(view);
btnCart = (Button) view.findViewById(R.id.btnCart);
}
}
Then override onBindViewHolder in your adapter (your adapter extends RecyclerView.Adapter).
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.btnCart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// call the opening of your dialog here
}
});
}

Set database object to be deleted in android

I've setup a database in android for my app however I'm stuck trying to delete a object within the database.
I'd like the button within BasicButtonsCard to delete the item that has been clicked on.
For example cardX holds data ABCD while cardY hold EFGH and on clicking the delete button on cardX, it deletes the card and its data.
Help is appreciated.
Code for input field:
public class note extends DialogFragment {
EditText memoryText, memoryTitle;
public interface NewPersonDialogListener{
void onFinishAddPersonDialog(String text, String title);
}
public note(){}
public Dialog onCreateDialog(Bundle savedInstanceState){
LayoutInflater i = getActivity().getLayoutInflater();
View rootview = i.inflate(R.layout.activity_note, null);
memoryText = (EditText)rootview.findViewById(R.id.memoryText);
memoryTitle = (EditText)rootview.findViewById(R.id.memoryTitle);
AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
b.setTitle("Add New Memory");
b.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String text = memoryText.getText().toString();
String title = memoryTitle.getText().toString();
NewPersonDialogListener activity = (NewPersonDialogListener)getActivity();
activity.onFinishAddPersonDialog(text, title);
}
});
b.setNegativeButton("Cancel", null);
b.setView(rootview);
return b.create();
}
}
Code that handles MainActivity in the app:
public class MainActivity extends AppCompatActivity implements note.NewPersonDialogListener{
ImageButton runCommand;
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
String[] mDrawerListItems;
MaterialListView mListView;
MemoryDataSource dataSource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mDrawerList = (ListView)findViewById(android.R.id.list);
dataSource = new MemoryDataSource(this);
mListView = (MaterialListView) findViewById(R.id.material_listview);
generateList();
mListView.addOnItemTouchListener(new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(CardItemView cardItemView, int i) {
}
#Override
public void onItemLongClick(CardItemView cardItemView, int i) {
}
});
mDrawerListItems = getResources().getStringArray(R.array.drawer_list);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mDrawerListItems));
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
break;
case 1:
intent = new Intent(MainActivity.this, bands.class);
startActivity(intent);
break;
case 2:
intent = new Intent(MainActivity.this, memory_vault.class);
startActivity(intent);
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
});
runCommand = (ImageButton)findViewById(R.id.runCommand);
runCommand.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
Intent i = new Intent(MainActivity.this, note.class);
startActivity(i);
*/
note noteFragment = new note();
noteFragment.show(getFragmentManager(), "tag");
}
});
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
toolbar,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View v){
super.onDrawerClosed(v);
invalidateOptionsMenu();
syncState();
}
public void onDrawerOpened(View v){
super.onDrawerOpened(v);
invalidateOptionsMenu();
syncState();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle.syncState();
}
public void generateList(){
dataSource.open();
List<memoryModel> list = dataSource.findMemory();
for (memoryModel model : list){
BasicButtonsCard card = new BasicButtonsCard(this);
card.setTitle(model.getmemoryTitle());
card.setDescription(model.getmemoryText());
card.setBackgroundColorRes(R.color.background_material_dark);
card.setDescriptionColorRes(R.color.abc_secondary_text_material_dark);
card.setTitleColorRes(R.color.abc_secondary_text_material_dark);
card.setLeftButtonText("LEFT");
card.setRightButtonText("RIGHT");
card.setDismissible(true);
card.setOnRightButtonPressedListener(new OnButtonPressListener() {
#Override
public void onButtonPressedListener(View view, Card card) {
Intent intent = new Intent(MainActivity.this, bands.class);
startActivity(intent);
}
});
card.setOnLeftButtonPressedListener(new OnButtonPressListener() {
#Override
public void onButtonPressedListener(View view, Card card) {
}
});
mListView.add(card);
}
}
#Override
public void onResume(){
super.onResume();
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case android.R.id.home: {
if (mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
}
default: return super.onOptionsItemSelected(item);
}
}
#Override
public void onFinishAddPersonDialog(String text, String title) {
dataSource.open();
memoryModel model = new memoryModel();
model.setmemoryText(title);
model.setmemoryTitle(text);
dataSource.create(model);
dataSource.close();
generateList();
}
}
I will assume that you already have a RecyclerView with a button on each row since you didn't mention that as a problem. You should have a view holder class, and in the constructor of that class you can set up your listeners.
class Holder extends RecyclerView.ViewHolder{
public Holder(View itemView){
super(itemView);
View button = itemView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int rowNumber = getPosition();
// call delete method here
}
});
}
public void bind(int index){
// ...
}
}
Solved the issue of deleting data from the database. Since it was contained in a cardview layout with a button all I needed to do was add a onclick listener which would do the following
dataSource.deleteMemory(model.getmemoryTitle());
dataSource.deleteMemory(model.getmemoryText());
mListView.remove(card);

How to add new items to popup menu after click

I have a button:
<Button
android:id="#+id/bot_button1"
android:layout_width="120dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:textSize="24sp"
android:text="#string/bot_button1_tx" />
This is my main activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.bot_button1);
button1.setOnClickListener(onClickListener);
Log.d(className, "onCreate");
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.bot_button1:
showPopupMenu(v, 1);
break;
}
}
};
private void showPopupMenu(final View v, Integer i){
PopupMenu popupMenu = new PopupMenu(MainActivity.this, v);
switch (i) {
case 1:
popupMenu.getMenuInflater().inflate(R.menu.menu1, popupMenu.getMenu());
break;
}
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
new AlertDialog.Builder(activity).
setTitle("TITLE").
setMessage("MESSAGE").
setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO: user specific action
dialog.dismiss();
}
}).create().show();
return true;
}
});
popupMenu.show();
}
How can I display more items when an item from the PopupMenu is selected (clicked)? Ideal case scenario: PopupMenu remains visible after selection, and a new PopupMenu appears right next to the selected item. OR Popup Menu expands to show the subitems.
I tried to introduce a second PopupMenu onMenuItemClick(), but it only replaces the first PopupMenu.
I used a new popup menu to solve this issue
public OnMenuItemClickListener listener = new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu2_3_3:
popupMenu2.getMenuInflater().inflate(R.menu.menu2_3_3, popupMenu2.getMenu());
popupMenu2.show();
popupMenu2.setOnMenuItemClickListener(listener2);

Categories

Resources