Reputation: 16340
I have set the onClick property of an EditText which is located in a fragment:
<EditText android:id="@+id/edittext1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:inputType="none" android:maxLines="1"
android:singleLine="true" android:layout_marginTop="16dp"
android:focusable="false"
android:longClickable="false"
android:clickable="true"
android:onClick="doSomething"
android:cursorVisible="false"
android:editable="false">
Then in the fragment class I have:
public void doSomething(View view) {
//show dialogfragment...
}
But the method doSomething
is grayed out and I get the warning 'Method doSomething is never used'.
Note: This code was originally in an activity and was working fine.
Is there another way to handle onClick in fragments?
Upvotes: 0
Views: 3782
Reputation: 3785
first initialize an EditText
instance in the top of your fragment
EditText et;
then
in your onCreateView()
add:
etEmployee=(EditText)rootView.findViewById(R.id.edittext1);
then implement your onClickListener()
et.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//what ever you need to do goes here
}
});
Note: in fragments you have to refer to the inflatedView
to be able to access your editText
in this case rootView.
also the code you are using doesn't work becouse here you are using fragments and using onClick
attribute in your xml would only make you able to use it in the MainActivity
that contain your fragment
.
hope this will help.
Upvotes: 1
Reputation: 12684
In your layout XML try specifying a tools:context="com.mypackage.path.MyFragment"
. Don't know if it'll fix it for 'onClick', but it has fixed similar issues for me in the past.
This goes in the top most 'ViewGroup' in your layout file, example:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.mypackage.path.MyFragment" />
Upvotes: 0
Reputation: 1005
You can always try to add a OnClickListener to the EditText if it does not matter to you in which way the function gets called.
edittext1 = (EditText) view.findViewById(R.id.edittext1);
edittext1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
doSomething();
}
});
Upvotes: 0
Reputation: 7214
If you add android:onClick="doSomething"
to your fragment then method will be invoked in your activity but not in Activity
. If you want the callback in your fragment add through pragmatically.
edittext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Your code.
}
});
Upvotes: 0