what is the replacement for onclick ( depecrated ) in kotlin? - android

I want use android:onClick to access the functions at MainActivity from activity_main.xml but it's deprecated. Is there another way or replacement for onClick?
Here the code:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:textSize="30dp"
android:id="#+id/btn00"
android:onClick="click"></Button></LinearLayout>
and my function at MainActivity
fun click(view: View){
Toast.makeText(applicationContext,"Clicked",Toast.LENGTH_SHORT).show
}
There is an error saying "Corresponding method handler 'public void click(android.view.View)' not found.

The XML error is because there is no context specified for your layout file. you can specify it in the root element of layout XML file as
tools:context="yourpackage.MainActivity"
This basically tells the XML to look for click function in MainActivity.
Other than that this code should run correctly, given that you have specified the correct XML layout in your Activity setContentView.
point worth noting is that there is always an option to do it
programmatically in your Activity onCreate
val button = findViewById<Button>(R.id.btn00)
button.setOnClickListener{
Toast.makeText(applicationContext,"Clicked",Toast.LENGTH_SHORT).show()
}

Thanks all for the help,
Turns out I place my function at the wrong place.
I'm sorry for the trouble.
Turn out it's just a petty mistake :D
Edit: Turns out i placed my fuction outside of the class

Related

findViewById Attribute in Fragment from the activity xml Not work [duplicate]

This question already has answers here:
findViewById in Fragment
(37 answers)
Closed 2 years ago.
How to access an attribute in the activity xml?
I want to use it in fragment.
for example : this is my activity xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:fab="http://schemas.android.com/apk/res-auto">
<androidx.constraintlayout.widget.ConstraintLayout
fab:layout_constraintTop_toTopOf="parent"
fab:layout_constraintLeft_toLeftOf="parent"
fab:layout_constraintRight_toRightOf="parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/layTitle"
android:layoutDirection="rtl"
android:background="#color/colorPrimary"
android:padding="#dimen/paddingTitle"
android:elevation="#dimen/elevationActivityTitle"
android:layout_alignParentTop="true">
<ImageView
fab:layout_constraintLeft_toLeftOf="parent"
fab:layout_constraintTop_toTopOf="parent"
fab:layout_constraintBottom_toBottomOf="parent"
android:layout_width="#dimen/imgActivityTitle"
android:layout_height="#dimen/imgActivityTitle"
android:id="#+id/btn_back"
android:src="#drawable/ic_back"
android:elevation="5dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<FrameLayout
android:id="#+id/frag"
android:layout_width="0dp"
android:layout_height="0dp"
fab:layout_constraintBottom_toBottomOf="parent"
fab:layout_constraintTop_toBottomOf="#+id/layTitle"
fab:layout_constraintLeft_toLeftOf="parent"
fab:layout_constraintRight_toRightOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
I want findViewByid ImageView in fragment
When I was searching for solution I got the following one:
TextView btn_back= (TextView) getView().findViewById(R.id.btn_back)
But, unfortunately it was not working for me.
You can use the interface to do it :
Create an interface names IBtnClick with one void method: "void onBtnClicked();"
use interface in activity like this:
IBtnClick iBtnClick= (IBtnClick)getActivity();
here getAtivity is our context, if it doesn't work use another scope context.
and use your method in button click listener like this
iBtnClick.onBtnClicked();
Now in your fragment you have to implements interface and
you can add any action you want in Overrided method.
Use either viewModel or interfaces to talk between activity and fragment. don't try to send the button to fragment but trigger it from there. That will prevent any leaks or null pointers.
Ok. You have some options.
Firstly, you can access these variables to directly in fragment like that.
MainActivity.java
TextView backButton;
backButton = findViewById(R.id.btn_back);
Fragment.java
((MainActivity) getActivity()).backButton
You can get current activity with getActivity() but Java compiler cannot understand which activity so have to cast to MainActivity.
Secondly, you can pass your activity instance to fragment. You can use constructors and newInstance() function. You can read that post Best practice for instantiating a new Android Fragment
In my opinion, I prefer second option because you guarantee these variables that include activity class. Some devices occur errors at first option. But second option uses more ram because you are passing your variables to another class.
The choice is yours
Try This code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.recharge_plane_fragment, container, false);
alertdialog_Listview=view.findViewById(R.id.alertdialog_Listview);
return view;
}
You can declare your TextView btn_back as static in activity
public static TextView btn_back;
btn_back = (TextView) findViewById(R.id.btn_back);
and get it in fragment
TextView btn_back = ((MainActivity)getActivity()).btn_back;

Why is it that my Android app doesn't run when I remove a TextView?

Well, it's basically a project a friend of mine started and I'm taking on what he left. If I remove this piece of code:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="<redacted>"
android:id="#+id/usernameTextView"
android:layout_marginBottom="100dp"
android:layout_gravity="center_horizontal"/>
The app will open but will force quit whenever I switch to another Activity.
If that piece of code is there, the app runs smoothly.
What could it be?
Check any code in onPause(), onStop(), onDestroy(), or generally in the place where you wrote the code of switching to another activity. Your TextView must have been called somewhere in your code, and now you removed it which will cause NullPointerException if it is being called anywhere in your activity.
You can also check your logcat to know what piece of code causes this issue.
You probably instantiating a usernameTextView TextView inside one of your activites. Go there, find and remove this line of code:
TextView textView = (TextView) findViewById(R.id.usernameTextView);
Go to your activity and remove the code relative to findViewById(R.id.usernameTextView)

Creating a fragment without instantiating it from java code

I have got a project which was developed by another person. In that there is a fragment but I cannot find who is instantiating it. Is it possible that a fragment could be created by the main activity through layout xmls? That is, without instantiating it in Java code using" new Fragment", is it possible to instantiate it through some xml or something? Because I have checked the Fragment constructor usage and it also doesn't show any other class calling it. But when I debug the code, the fragment does get called. If its possible, how can I pass arguments from an activity to this fragment? Because if its created using "Fragment f = new Fragment" I could use the setArguments method or even pass it through constructor. But on a situation like this, how can I pass values from an activity to this fragment? Please advice.
Yes, it's possible, see docs. For instance, from that page:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment android:name="com.example.android.fragments.HeadlinesFragment"
android:id="#+id/headlines_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.android.fragments.ArticleFragment"
android:id="#+id/article_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
Is it possible that a fragment could be created by the main activity
through layout xmls?
Yes, this is a static Fragment. If you check the layout files, you should see a <fragment /> tag:
<fragment
android:id="#+id/example_fragment"
android:name="com.example.staticfragexample.MyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
There will then be a corresponding MyFragment class. To access it, you would use getFragmentManager().findFragmentById(R.id.example_fragment);
You are saying that the fragments are not instantiated through java code. That means they must have been declared in xml and are instantiated as soon as the activity gets created like this -
<fragment android:name="com.test.SampleFragment"
android:id="#+id/sample_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In this case you can't use setArguments() , but instead use some other mechanism to send data to the fragments .

How to Implement OnTouch Listener in XML

As i know we can define onClick tag in xml after writing in xml we can use in java code easily by name that specify in xml eg
<Button android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="myClick" />
public void myClick(View v) {
// does something very
}
1) Is any way to define onTouch in XML if yes then how to use ???
2) Or any other way to implement onTouch Listener inside onClick listener;
here my goal is to interact more than 100 buttons without defining Buttons name as mention below: and also have onTouch functionality...
Button mbutton;
mbutton = (Button)findViewbyId(R.id.button);
Thanks
1) Is any way to define onTouch in XML if yes then how to use ???
No, there is no default attribute provided by android that lets you define touch event in xml file, you have to write the method in .java file.
2) Or any other way to implement onTouch Listener inside onClick listener;
No, you cannot implement onTouch() inside onClick() because onClick event gets called when you touch or say click or tap the screen for the first time and performs the event when you release touch. But it is not able to detect the movement of your touch i.e. ACTION_DOWN, ACTION_UP etc.
So if you want to implement onTouch() event, you will have write it on your own.
You can write some mechanism that can let you implement onTouch() event easily. But instead of doing that I'd suggest you to use Butterknife library which will let you write onTouch() method easily just by defining annotation. Here's the code how they have binded onTouch() in annotation (in case you want to write your own mechanism).
Hope this helps some one
You can easily do it using databinding:
step1
public class DataBidingAdapter{
#SuppressLint("ClickableViewAccessibility")
#BindingAdapter("touchme")
public static void setViewOnTouch(TextView view, View.OnTouchListener listener) {
view.setOnTouchListener(listener);
}
}
step 2 in xml
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="handlers"
type="com.user.handlers.Handlers" />
</data>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
>
<EditText
android:id="#+id/search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/search_for_chats_title"
app:touchme="#{handlers.searchPatient}" />
</FrameLayout>
</linearLayout>
</layout>
step 3
public class Handler{
public boolean searchPatient(View v, MotionEvent event) {
if (MotionEvent.ACTION_UP == event.getAction()) {
//your code
}
return true;
}
}
As far as I know, you cant put code directly into XML. Please correct me if I am wrong. You must have code in the Activitys Class.

Including Package In Fragment Widget .XML

I'm adding a fragment called ZipInputFragment within the XML file of one of my activity's.
<fragment
android:id="#+id/zipCodeFragment"
android:layout_gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
class="com.markf.application.ZipInputFragment"
tools:layout="#layout/fragment_zip_input" />
This runs fine. The issue is that I have a separate package called non_activity where all of my fragments are stored. So when I place the ZipInputFragment in this package, my application crashes. I know that it's because of this line of code in my widget:
class="com.markf.application.ZipInputFragment"
The issue is that it's not acknowledging the fact that my Fragment is now in a separate package. Does anyone the syntax that would include my non_activity package in the widget? Thank you.
just use this instead then:
<fragment
android:id="#+id/zipCodeFragment"
android:layout_gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
class="com.markf.application.non_activity.ZipInputFragment"
tools:layout="#layout/fragment_zip_input" />
You just need to add the fully qualified package name to get it to work.

Categories

Resources