Android: onClick = "onRadioButtonClicked" has the same name as the function. I can not understand why he does not recognize it.
The poblem is in xml file, " Cannot resolve symbol 'onRadioButtonClicked' " on the Android: onClick = "onRadioButtonClicked" line
I followed this
My xml file
<RadioGroup
android:id="#+id/radioGroupLag"
android:checkedButton="#+id/radioButtonEnglish">
<TextView
android:id="#+id/textView_lang"
android:text="#string/txt_language"
android:textSize="20sp"
android:textStyle="bold"/>
<RadioButton
android:id="#+id/radioButtonGreek"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/RadioButtonGreek"
android:onClick= "onRadioButtonClicked"
android:textSize="20sp"
/>
<RadioButton
android:id="#+id/radioButtonEnglish"
android:text="#string/RadioButtonEnglish"
android:onClick= "onRadioButtonClicked"/>
<RadioButton
android:id="#+id/radioButtonGerman"
android:text="#string/RadioButtonGerman"
android:onClick= "onRadioButtonClicked"/>
</RadioGroup>
My fun in the Fragment:
private fun onRadioButtonClicked(view: View) {
if (view is RadioButton) {
val checked = view.isChecked
// Check which radio button was clicked
when (view.getId()) {
R.id.radioButtonGreek->{
if (checked) {
changeLag()
}
}
R.id.radioButtonGerman ->{
if (checked) {
changeLag()
}
}
R.id.radioButtonEnglish-> {
if (checked) {
changeLag()
}
}
}
}
}
End i call the fun in onCreateView
onRadioButtonClicked(binding.radioGroupLag)
The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:
Be public
Return void
Define a View as its only parameter (this will be the View that was clicked)
Quote from the guide you linked (emphasis mine). Make your method public.
Related
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
I want to validate form login Kotlin with Application Structure Model–view–viewmodel
I used ViewModel with Data Binding and LiveData, Create a variable in the XML file for Two-Way Data
I can validate when empty field but I don't know How to set error for editText when user change EditText invited format or worng characters
activity_main.xml
<data><variable
name="viewModel"
type="com.validateform.LoginViewModel" />
</data>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/lay_username"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:hint="Username"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/edt_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#={viewModel.username}" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/lay_password"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:hint="Password"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/edt_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#={viewModel.password}" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/btn_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="#{()-> viewModel.submitLogin()}"
android:text="Submit"/>
MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var viewModel : LoginViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Binding
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
// ViewModel
viewModel = ViewModelProviders.of(this).get(LoginViewModel::class.java)
binding.lifecycleOwner = this
binding.viewModel = viewModel
initObserver()
}
private fun initObserver() {
viewModel.errorMessage.observe(this, Observer { message ->
Snackbar.make(binding.btnSubmit, message, Snackbar.LENGTH_LONG).show()
})
}
}
LoginViewModel.kt
class LoginViewModel : ViewModel() {
val username = MutableLiveData()
val password = MutableLiveData()
private val _errorMessage = MutableLiveData()
val errorMessage : LiveData
get() = _errorMessage
fun submitLogin() {
validateForm()
}
private fun validateForm() : Boolean {
var result = true
if (username.value.isNullOrEmpty()) {
_errorMessage.value = "User Required"
result = false
}
if (password.value.isNullOrEmpty()) {
_errorMessage.value = "Password Required"
result = false
}
return result
}
}
You need to return error message as a string resource to support localization. Also, you need to create binding adapter for it.
View model sample
interface LoginViewModel {
val errorMessage: LiveData<Int>
}
Binding adapter sample
#BindingAdapter("error")
internal fun TextInputLayout.setError(#StringRes errorRes: Int) {
error = errorRes.takeUnless { it == ID_NULL }?.let { resources.getString(it) }
}
Layout
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/lay_username"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:hint="Username"
app:errorEnabled="true"
bind:error="#{ vm.errorMessage }">
</com.google.android.material.textfield.TextInputLayout>
Note: you don't need flag app:errorEnabled="true" if your provide helper text. It main purpose to reserve space for the message.
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.
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.
Despite having the method onButtonHomeClick declared in the Java file MainActivity, when I attempt to reference the method in the XML I receive the error message: "Method onButtonHomeClick in MainActivity has incorrect signature". Both of them are below, and I cannot for the life of me figure out why it is returning such an error, especially since attempting to navigate to the declaration by Ctrl clicking onButtonHomeClick in the XML file navigates to the method in the Java class.
And it's definitely struggling to find the method, as the Android Monitor returns a fatal error when attempting to assign the behaviour to the button.
<!-- XML file -->
<item
android:id="#+id/button_home"
android:orderInCategory="100"
android:icon="#drawable/home"
android:title="Home"
android:onClick="onButtonHomeClick"
app:showAsAction="always"
/>
//Java method
public void onButtonHomeClick(View v){
Intent intent = new Intent(this, MainActivity.class);
}
Clean your project and then make sure the method onButtonHomeClick() is declared as public void.
Your On Click Method has Invalid Arguments for MenuItem. For MenuItem, it is
public void onClickMethod(MenuItem menuItem) {
// Your code here
}
Whereas public void onClickMethod(View view) {...} is for View present in your activity layout.
Also just creating an Intent will not start the Activity. For starting the activity you should pass your intent to startActivity().
you need to add startActivity(intent); in your method, so it should be something like this:
public void onButtonHomeClick(View v){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
I tried your code with startActivity(intent); included and it works just fine
in kotlin:
<android.support.v7.widget.AppCompatButton
android:id="#+id/mRecharge_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:textSize="18sp" />
in your activity create public fun onClick
public fun onClick(view: View?) {
// do ur logic here
}
You must also define the android: onClick method to all views. Remember that the click method name is the same in all views.
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layoutDirection="rtl" >
<RadioButton
android:id="#+id/radioButton_score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Score"
android:onClick="OnClickView"/>
<RadioButton
android:id="#+id/radioButton_discoun_percent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Discoun Percent"
android:onClick="OnClickView" />
</RadioGroup>
public void OnClickView(View view) {
switch(view.getId()){
case R.id.radioButton_score:
Toast.makeText(this, "click Score",
Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton_discoun_percent:
Toast.makeText(this, "click Discoun Percent",
Toast.LENGTH_SHORT).show();
break;
}
}
Did you remember to include in your MainActvity.java file the import for the View class? (It's not imported by default.)
import android.view.View;