How to display both icon and title of action inside ActionBar? - android-layout

I need to display both icon and title of action inside ActionBar.
I've tried "withText" option, but it has no effect.

'always|withText' will work if there is sufficient room, otherwise it will only place icon. You can test it on your phone with rotation.
<item android:id="#id/menu_item"
android:title="text"
android:icon="#drawable/drawable_resource_name"
android:showAsAction="always|withText" />

You can create actions with text in 2 ways:
1- From XML:
<item android:id="#id/resource_name"
android:title="text"
android:icon="#drawable/drawable_resource_name"
android:showAsAction="withText" />
When inflating the menu, you should call getSupportMenuInflater() since you are using ActionBarSherlock.
2- Programmatically:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, ID, POSITION, TEXT);
item.setIcon(R.drawable.drawable_resource_name);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
Make sure you import com.actionbarsherlock.view.Menu and com.actionbarsherlock.view.MenuItem.

What worked for me was using 'always|withText'. If you have many menus, consider using 'ifRoom' instead of 'always'.
<item android:id="#id/resource_name"
android:title="text"
android:icon="#drawable/drawable_resource_name"
android:showAsAction="always|withText" />

The solution I find is to use custom action Layout:
Here is XML for menu.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:Eventapp="http://schemas.android.com/apk/res-auto">
<!-- This is a comment. -->
<item
android:id="#+id/action_create"
android:actionLayout="#layout/action_view_details_layout"
android:orderInCategory="50"
android:showAsAction = "always"/>
</menu>
The Layout is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:gravity="center"
android:text="#string/create"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:gravity="center"
android:src="#drawable/ic_action_v"/>
</LinearLayout>
this will show the icon and the text together.
To get the clickitem the the fragment or activity:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
//super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_details_fragment, menu);
View view = menu.findItem(R.id.action_create).getActionView();
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT).show();
}
});
}

If any1 in 2017 is wondering how to do this programmatically, there is a way that i don't see in the answers
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

You can add button in toolbar
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:title="title">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="16dp"
android:background="#color/transparent"
android:drawableRight="#drawable/ic_your_icon"
android:drawableTint="#drawable/btn_selector"
android:text="#string/sort_by_credit"
android:textColor="#drawable/btn_selector"
/>
</android.support.v7.widget.Toolbar>
create file btn_selector.xml in drawable
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:color="#color/white"
/>
<item
android:color="#color/white_30_opacity"
/>
java:
private boolean isSelect = false;
OnClickListener for button:
private void myClick() {
if (!isSelect) {
//**your code**//
isSelect = true;
} else {//**your code**//
isSelect = false;
}
sort.setSelected(isSelect);
}

Some of you guys have great answers, but I found some additional thing. If you want create a MenuItem with some SubMenu programmatically:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu subMenu = menu.addSubMenu(0, Menu.NONE, 0, "Menu title");
subMenu.getItem().setIcon(R.drawable.ic_action_child);
subMenu.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
subMenu.add(0, Menu.NONE, 0, "Subitem 1");
subMenu.add(0, Menu.NONE, 1, "Subitem 2");
subMenu.add(0, Menu.NONE, 2, "Subitem 3");
return true;
}

Try adding a TextView to the menubar first and using setCompoundDrawables() to place the image on whichever side you want. Bond click activity to the textview in the end.
MenuItem item = menu.add(Menu.NONE, R.id.menu_item_save, 10, R.string.save);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS|MenuItem.SHOW_AS_ACTION_WITH_TEXT);
TextView textBtn = getTextButton(btn_title, btn_image);
item.setActionView(textBtn);
textBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// your selector here }
});
You can literally customize everything here:
public TextView getTextButton (String btn_title, Drawable btn_image) {
TextView textBtn = new TextView(this);
textBtn.setText(btn_title);
textBtn.setTextColor(Color.WHITE);
textBtn.setTextSize(18);
textBtn.setTypeface(Typeface.create("sans-serif-light", Typeface.BOLD));
textBtn.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
Drawable img = btn_image;
img.setBounds(0, 0, 30, 30);
textBtn.setCompoundDrawables(null, null, img, null);
// left,top,right,bottom. In this case icon is right to the text
return textBtn;
}

Using app:showAsAction="always|withText".
I am using Android 4.1.1, but it should applicable anyway.
Mine look like below
<item
android:id="#+id/action_sent_current_data"
android:icon="#drawable/ic_upload_cloud"
android:orderInCategory="100"
android:title="#string/action_sent_current_data"
app:showAsAction="always|withText"/>

Follow these steps:
Add the Action Bar instance in the Java Code final ActionBar
actionBar = getActionBar();
Enable the Home Display Option
actionBar.setDisplayShowHomeEnabled(false);
Add the following code in the respective activity's manifest file
android:logo=#drawable/logo and android:label="#string/actionbar_text"
I think this will help you

Related

popup window on my map Fragment android studio

can anyone help me with this i want to show a popupwindow on top of my map fragment when i click on a button it will display a popupwindow that contains text for example the text will be how the user will navigate the map
public class FirstFragment extends Fragment {
public FirstFragment() {
// require a empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.maps); //use SuppoprtMapFragment for using in fragment instead of activity MapFragment = activity SupportMapFragment = fragment
mapFragment.getMapAsync(new OnMapReadyCallback() {
public void onMapReady(#NonNull GoogleMap googleMap) {
GoogleMap mMap = googleMap;
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setBuildingsEnabled(true);
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(requireContext()));
mMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(requireContext(), R.raw.style));
CameraPosition googlePlex = CameraPosition.builder()
.target(new LatLng(14.5768, 121.0332))
.zoom(15)
.bearing(0)
.tilt(60)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 4000, null);
mMap.addMarker(new MarkerOptions()
.icon(bitmapDescriptorFromVector(getActivity(), R.drawable.ic_baseline_location_city_24))
.position(new LatLng(14.5768, 121.0332))
.title("Mandaluyong");
KmlLayer layer = null;
try {
layer = new KmlLayer(mMap, R.raw.mandaluyong, getContext());
} catch (Exception e) {
e.printStackTrace();
}
for (KmlPlacemark placemark : layer.getPlacemarks()) {
}
layer.addLayerToMap();
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
mMap.addMarker(new MarkerOptions()
.position(point)
.title("Home")
.snippet("Your PlaceMarker!!!"));
this is the xml file i've added a floating action button on it now when click it i want to display a popup window that will show on top of my map fragment ive tried different things and it crashes or doesnt show the popup ive decided to ask here because i am stuck in this part
}
<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"
tools:context=".MainActivity"
xmlns:app="http://schemas.android.com/apk/res-auto">
<fragment
android:id="#+id/maps"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/infobutton"
android:src="#drawable/ic_baseline_info_24"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="30dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:layout_marginBottom="97dp"
android:clickable="true"
android:rotation="0" />
<FrameLayout
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="300dp">
</FrameLayout>
</RelativeLayout>
here are the java and xml files of the map fragment that i used
[maps app pic][1]
[1]: https://i.stack.imgur.com/xaBIR.png

How to define setOnClickListner in a popup view(Android Studio)?

So, I have made a button which on clicking opens a popup window with two buttons inside it, but now I am not able to assign setOnClickListner to those two buttons inside the OnCreateMethod as I did for all the other buttons in the main window (If I do then the app Stops responding) as till that time the buttons are not actually there(I think, that's the reason), So could you please help me assign on click listner to those buttons.
Here is the code for the popupWindow excution:
public void onButtonShowPopupWindowClick(View view) {
// inflate the layout of the popup window
LayoutInflater inflater = (LayoutInflater)
getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.confirm_number_popup, null);
hideSoftKeyboard(Register.this);
// create the popup window
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
boolean focusable = true; // lets taps outside the popup also dismiss it
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, false);
// show the popup window
// which view you pass in doesn't matter, it is only used for the window token
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
// dismiss the popup window when touched
popupView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
popupWindow.dismiss();
return true;
}
});
}
Here is the layout file for the popup view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/white">
<Button
android:id="#+id/btn_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/green_shade_1"
android:text="#string/edit"
android:textSize="16sp"
android:layout_below="#id/txt_edit"
android:layout_alignParentStart="true"
android:layout_marginStart="20dp"
android:background="#color/white"
style="?android:attr/borderlessButtonStyle"/>
<Button
android:id="#+id/btn_Ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/green_shade_1"
android:text="#string/ok"
android:textSize="16sp"
android:layout_below="#id/txt_edit"
android:layout_alignParentEnd="true"
android:layout_marginEnd="20dp"
android:background="#color/white"
style="?android:attr/borderlessButtonStyle"/>
</RelativeLayout>
Please tell me if you are not able to understand the question or if any else code is needed.
Thank You!
Edit: I have already tried adding this in my OnCreate but it doesen't work:
Button btnEdit = findViewById(R.id.btn_edit);
btnEdit.setOnClickListener(v -> {
//The function
});
use
Button btn1 = popupView.findViewById(R.id.btn_edit);
btn1.setOnClickListener{}

Android: RecyclerView's CardView Not Showing Every Time

I have a RecyclerView in MainActivity that shows a list of CardViews and that is working properly. A click on the CardView finishes the RecyclerView Activity and launches a Detail Activity that shows the clicked on CardView in a new RecyclerView list. The Detail Activity is used only to show that single CardView in a RecyclerView (I do this so I can use RecyclerView's ItemTouchHelper.SimpleCallback code on the CardView for easy left swipe for the user).
Here is the problem: I hit the left caret on the Detail Activity's Toolbar to return to the MainActivity. Then a click on the exact same CardView brings the user back to the Detail Activity. But this time only the background View (a border) is showing. The view of the CardView and its database data is completely missing.
The error appears to happen randomly. I can click to go from the MainActivity to the Detail Activity back and forth 5 times successfully and then on the sixth try, no CardView will show in the Detail Activity. Or I'll click two times successfully and then the third time, the CardView in the Detail Activity will not show. Note the left caret click in Detail Activity uses onBackPressed() so the Detail Activity finishes. So I don't think there should be any backstack issues. I also tried to adjust the xml height for the CardView to match_parent rather than wrap_content but no luck. The Detail Activity's ViewModel to Repository to Dao returns a List wrapped in LiveData. Perhaps there is an observer problem with the ViewModel, but I thought the observer gets removed/destroyed when the Detail Activity is destroyed? What am I missing here?
Adapter
...
itemHolder.cardView.setOnClickListener(view -> {
Card adapterItem= TodosAdapter.this.getItem(itemHolder.getAdapterPosition());
int adapPos = itemHolder.getAdapterPosition();
if (adapPos !=RecyclerView.NO_POSITION) {
onItemClick(adapPos, adapterItem);
}
});
MainActivity
...
public void onItemClick(int clickPos, Card cardFromClick) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("TAG","fromMain");
intent.putExtra("itemFromMain", cardFromClick);
startActivity(intent);
finish();
DetailActivity
...
public class DetailActivity extends AppCompatActivity {
private int cardId = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
// Get a new or existing ViewModel from the ViewModelProvider.
detsViewModel = new ViewModelProvider(this).get(CardViewModel.class);
Toolbar toolbar = findViewById(R.id.toolbar);
// The left caret is for Up navigation to the previous activity
// for OS versions 4.0 and earlier.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationIcon(R.drawable.ic_action_previous_item);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
String classname = extras.getString("TAG");
// The user clicked on a Card in the MainActivity
if (classname != null && classname.equals("fromMain")) {
card = extras.getParcelable("itemFromMain");
if (card != null) {
cardId = card.getId(); // card data is stored in Room database.
}
}
}
detsViewModel.getSingleCard(cardId).observe(this, singleAdapterList -> {
adapter2.setCardList(singleAdapterList);
});
}
activity_details.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:background="#FFFFFF"
tools:context=".DetailsActivity" >
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" >
</include>
<RelativeLayout
android:id="#+id/todoListLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar" >
<TextView
android:id="#+id/Card"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:text="Card"
android:textStyle="bold"
android:textColor="#color/text_primary"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_centerHorizontal="true" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/details_recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/Card"
android:scrollbars="vertical" />
<TextView
android:id="#+id/skytext5"
android:text="Cards"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/details_recyclerview"
android:background="#color/colorPrimary"
android:textAppearance="?android:attr/textAppearanceMedium"
android:clickable="true"
android:focusable="true" />
</RelativeLayout>
DetailsAdapter
...
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.details_list_item, parent, false);
}
private List<Card> oneCardList
public void setCardList(List<Card> singleCardList) {
if (oneCardList != null) {
oneCardList.clear();
this.oneCardList = singleCardList;
} else {
// First initialization
this.oneCardList = singleCardList;
}
}
details_list_item.xml
...
<FrameLayout
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/detsinglecard_view"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:foreground="?android:attr/selectableItemBackground"
android:background="#FFFFFF"
tools:context=".DetailActivity">
<RelativeLayout
android:id="#+id/view_background2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
...
</RelativeLayout>
<RelativeLayout
android:id="#+id/view_foreground2"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#color/colorFlLabelFinal" >
<androidx.cardview.widget.CardView
android:id="#+id/cardview_dets"
android:layout_height="match_parent"
android:layout_width="match_parent"
...
}
ViewModel
...
LiveData<List<Card>> getSingleCard(int cardId) {
return repository.getSingleCard(cardId);
}
Repository
...
public LiveData<List<Card>> getSingleCard(int cardId) {
return quickcardDao.getSingleCard(cardId);
}
Dao
...
#Query("SELECT * FROM cards WHERE cardId = :cardId LIMIT 1")
LiveData<List<Card>> getSingleCard(int cardId);
So if the data does not change then going back to the same DetailActivity will not refresh the View. The answer was to re-use the LiveData (rather than re-loading the LiveData again from the database) if the data has not changed. See the Android Developers Architecture Components guide for ViewModel, "Implement a ViewModel" section for the "loadUsers()" example that solved my problem: https://developer.android.com/topic/libraries/architecture/viewmodel.

How to add switch button in navigation drawer

I want to use switch button in navigation drawer for adding and removing fragment from main layout.
this my code-
menuitem.xml`
<group
android:id="#+id/drawer_group1"
android:checkableBehavior="single">
<item
android:id="#+id/nav_timer"
android:icon="#drawable/ic_timer"
android:title="Timer">
</item>
<item
android:id="#+id/addFragment_Bt"
app:actionViewClass="android.widget.Switch"
android:title="Most Used" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_settings"
android:title="Settings">
</item>
</group>`
MainActivity.class
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
switch (menuItem.getItemId()) {
case R.id.addFragment_Bt:
Switch switchCompat = findViewById(R.id.addMostUsed_Bt);
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.Most_Used_Fragment_container);
if (isChecked == true) {
if (fragment != null) {
fragmentManager.popBackStack();
}
}
}
});
break;
}
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
for now i am just trying to remove already added fragment.
menuitem.xml
<item android:id="#+id/nav_switch"
app:actionLayout="#layout/switch_menu"
android:title="Send"
android:icon="#drawable/ic_menu_send"/>
switch_menu switch_menu is layout for switch.
switch_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.SwitchCompat
android:id="#+id/switch_id"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:text=""/>
</LinearLayout>
Access Switch into activity:--
SwitchCompat switch_id;
switch_id = actionView.findViewById(R.id.switch_id);
switch_id.setChecked(true);
switch_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), switch_id.isChecked()? "is checked!!!" : "not checked!!!",Toast.LENGTH_SHORT).show();
}
});
The output using above code is:
I hope its work for you.
This Works for me.
///This is menu item.
<item
android:id="#+id/darkModeMenu"
android:title="Dark Mode"
android:icon="#drawable/ic_darkmode"
app:actionViewClass="androidx.appcompat.widget.SwitchCompat"
></item>
//write this on the on create() method of Activity.
val menuItem = navigationView.menu.findItem(R.id.darkModeMenu)
val switch_id = menuItem.actionView as SwitchCompat
switch_id.setChecked(true)
switch_id.setOnClickListener(View.OnClickListener {
Toast.makeText(
applicationContext,
if (switch_id.isChecked()) "is checked!!!" else "not checked!!!",
Toast.LENGTH_SHORT
).show()
})
I tried these methods but not works. After an hour of research. Finally, I found an answer.
Keep the focus on my point
First, add switch in the activity_main_drawer. Where your other drawer menu items
<item
android:id="#+id/app_bar_switch"
android:title="Switch"
app:actionLayout="#layout/switch_item"
app:showAsAction="always" />
and add below is XML by creating #layout/switch_item. Make sure to add id #+id/darkModeSwitch to your switch button. If XML creates automatically then just add the id to switch button.
<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">
<Switch
android:id="#+id/darkModeSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
tools:ignore="UseSwitchCompatOrMaterialXml" />
</RelativeLayout>
And finally, add the below java code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Code starts here
NavigationView navigationView = binding.navView; // your navigation drawer id
MenuItem menuItem = navigationView.getMenu().findItem(R.id.app_bar_switch); // first insialize MenuItem
#SuppressLint("UseSwitchCompatOrMaterialCode") Switch switchButton = (Switch) menuItem.getActionView().findViewById(R.id.darkModeSwitch);
// if you are using Switch in your #layout/switch_item then use Switch or use SwitchCompact
switchButton.setOnCheckedChangeListener((compoundButton, b) -> {
if (b){
Toast.makeText(this, "True", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "False", Toast.LENGTH_SHORT).show();
}
});
}
I hope it helps.

changing an edit text from another activiy after clicking a button

Okay so I'm new at programming, and for a school project I have to make a coffee shop app in android studio.
What I want to know, is how can I after clicking a button, edit a space for text to add text about the item they will buy but place it in another activity.
The thing is I want to make a kind of add to cart thing, and after going to the cart tab, there is an edit text where you see how much the account will be.
Can anyone help me with this??
You could use the Alert Dialog with Edit Text and pass the values using Shared Preference.
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater=MainActivity.this.getLayoutInflater();
//this is what I did to added the layout to the alert dialog
View layout=inflater.inflate(R.layout.editxml,null);
alert.setView(layout);
alert.setTitle("Enter Name");
final EditText usernameInput=(EditText)layout.findViewById(R.id.editText1);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
//do your stuff here
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
editxml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/editText1" />
</LinearLayout>

Resources