Android fragments onClick connect with method - android

I have the problem with connect method of button in fragment.
It doesn't work ... my application is always closed when I click a button.
In normal activity it work correctly, but why not in fragments? How can I repare it?
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="green"
android:text="#string/green" />
and
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.menu1_layout, container, false);
return rootview;
}
and my method green
public void green(View v){
//here everything is good
}
import android.view.View.OnClickListener; is marked "is never used"

You cannot do this since there is no context reference to a Fragment without the Activity. So therefore this is only possible in an Activity not a Fragment. Important thing to note here is that your Fragment must call getActivity() to find a reference to the context, since a fragment can be placed in any Activity fragment's themselves really have no context so referencing a Fragment's method in xml will not be possible in this respect.
Directly from Android :
public static final int onClick added in API 4
Name of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View. For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity).
Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.
This may also be a reference to a resource (in the form "#[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
Constant Value: 16843375 (0x0101026f)
UPDATE
Just Use this then:
Button button = (Button) getView().findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Move your green(View v) method logic here instead of calling green(v)
}
});
UPDATE 2
your fragment code should be doing this before anything else:
public class menu1_fragment extends Fragment {
View rootview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.menu1_layout, container, false);
return rootview;
}
// Probably safer for you to use onViewCreated(View, Bundle)
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
// use rootView or getView()
Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Move your green(View v) method logic here instead of calling green(v)
}
});
}
}
you cannot reference a UI element before the View is inflated, which was the cause of your error. Alternatively you can use onActivityCreated(Bundle savedInstanceState).

Related

How do i assign view in onCreate method in an activity android

I am having the following method which passes View
private void doSomething(View view){ }
The problem am having is how do i call this view in onCreate method in an Activity, i will have to pass the view
For Example
View view;
doSomething(view)
How do is assign view/instantiate view, am using getView() but its not working
Like
view = getView()
For Example in fragments onViewCreatedMethod has an argument view which i can assign to the method when am calling it. Example below
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
doSomething(view);
}
Is it possible to do that inside onCreate method in fragment, can I parse the View arguments in onCreate method in activity
In your onCreate method, once you've called setContentView, you can use findViewById to get whatever View you want. If you want the root view for some reason, you can pass android.R.id.content.
For example:
#Override
public void onCreate(Bundle savedInstanceState) {
// Replace your_layout_id with your Activity layout ID
setContentView(R.layout.your_layout_id);
View rootView = findViewById(android.R.id.content);
// Replace with whatever ID/View type you have in your code
// Button and your_button_id are just examples
Button button = findViewById(R.id.your_button_id);
}

Open an activity from a Fragment in Android

Whenever I use or implement onClickListner in Fragment, the application crashes. I have tried all the methods like implementing the fragment class using on click in XML but the application crashes all the time. Please help me with this. I don’t even write anything in the onClick override method and still, the application crashes.
Button btn_edit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.multi_frag,container,false);
btn_edit=(Button)rootView.findViewById(R.id.edit);
btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return inflater.inflate(R.layout.activity_account,container,false);
}
The application is crashing because you are returning a different view and finding the button in a different view.
// In below line you are using R.layout.multi_frag
View rootView=inflater.inflate(R.layout.multi_frag,container,false);
btn_edit=(Button)rootView.findViewById(R.id.edit);
btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
// And here, you are returning R.layout.activity_account.
return inflater.inflate(R.layout.activity_account,container,false);
You cannot use two layouts within one fragment. Check the right layout which contains the button and use that layout in both of the places.

Fragment with button clicks

Since, i am new to android, i am trying to learn fragments and how they work.I tried to make a length converter app which basically converts meter to centimeters.Simple, right?
Now I have two portions of the activity,one being the two edittexts which are the part of the activity layout, while the other one being the fragment.
This fragment basically contains keypad, in short, Numbers and operators displayed on it. Like a normal calci would have.
Now i read about the fragment life cycle and how it is supposed to work.
So The first thing that i did was to put everything in onCreateView method.
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
getRootView=inflater.inflate(R.layout.calci_keyboard,container,false);
GridLayout gridLayout=(GridLayout) getRootView.findViewById(R.id.calciKeyboardGrid);
for(int i=0;i<gridLayout.getChildCount();i++){
b=(Button)gridLayout.getChildAt(i);
b.setBackground(getResources().getDrawable(R.drawable.button_dark_gradient));
b.setOnClickListener(this);
}
return getRootView;
}
The thing is that, click events work but edittext settext doesn't seem to work. Edittexts are behaving weirdly.
Now, to remove that i thought i am accessing the Activity UI's , so i should do this inside onActivityCreated function ,So, i tried this too.
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
getRootView=inflater.inflate(R.layout.calci_keyboard,container,false);
return getRootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
#SuppressLint("InflateParams") View getView=(GridLayout) LayoutInflater.from(getActivity()).inflate(R.layout.calci_keyboard,null,false);
GridLayout gridLayout=(GridLayout) getView.findViewById(R.id.calciKeyboardGrid); // i Logged this obj and it was there
for(int i=0;i<gridLayout.getChildCount();i++){
b=(Button)gridLayout.getChildAt(i);
b.setBackground(getResources().getDrawable(R.drawable.button_dark_gradient));
b.setOnClickListener(this);
}
}
When i do things this way i don't seem to get my clicks working?
How am i supposed to do this problem? Can't find any solution.
Go easy on me,Thanks :)
Below one shows my onClick event:.
public void onClick(View view) {
View focussedChild=getActivity().getCurrentFocus();
switch (view.getId()){
case R.id.calciKeyboardNine:{
if (focussedChild instanceof EditText) {
firstPart=new StringBuilder("");
secondPart=new StringBuilder("");
EditText editText=(EditText)focussedChild;
if(focussedChild.getId()==R.id.lengthConverterFirst){
if(!TextUtils.isEmpty(firstPart.toString()))
firstPart.replace(0,firstPart.length()-1,editText.getText().toString()+"9");
firstPart.append("9");
editText.setText(firstPart.toString());
editText.setSelection(editText.length());
int a=Integer.parseInt(firstPart.toString());
a=a*100;
editText=getActivity().findViewById(R.id.lengthConverterSecond);//second edit text
editText.setText(Integer.toString(a));
editText.setSelection(editText.length());
}else if(focussedChild.getId()==R.id.lengthConverterSecond){
if(!TextUtils.isEmpty(secondPart.toString()))
secondPart.replace(0,secondPart.length()-1,editText.getText().toString()+"9");
secondPart.append("9");
editText.setText(secondPart.toString());
editText.setSelection(editText.length());
double a=Integer.parseInt(firstPart.toString());
a=a/100;
editText=getActivity().findViewById(R.id.lengthConverterFirst);//first edit text
editText.setText(Double.toString(a));
editText.setSelection(editText.length());
}
}
}
}
}
Now, to remove that i thought i am accessing the Activity UI's , so i should do this inside onActivityCreated function ,So, i tried this too - it didn't work because onActivityCreated() is method of fragment not activity.
try this - just make your edittexts static in activity and then you can access them in fragment by the activity's name like MainActivity.editText(). hope this helps

switching activities with textview

am trying to make the text under my login button "no account yet? signup now" when clicked to send me to my RegisterFragment.so i added an OnClickListener for it like this in my LoginFragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TextView signup = (TextView) getView().findViewById(R.id.signup);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginFragment.this.startActivity(new Intent(getActivity(), RegisterFragment.class));
}
});
but when i run the code the app crashes on this line
TextView signup = (TextView) getView().findViewById(R.id.signup);
this is my fragment_login.xml file
<TextView android:id="#+id/signup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:text="No Account Yet? Signup_now"
android:gravity="center"
android:textSize="16dp"
android:clickable="true"/>
please guys i really need your help.
onCreateView() method is responsible for creating view, so you should first create it.
You can't directly use getView() inside onCreateView().
You need to inflate it first like
View view = inflater.inflate(R.layout.my_layout, container, false);
Then use
TextView signup = (TextView) view.findViewById(R.id.signup);
So full code should look like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_layout, container, false);
TextView signup = (TextView) view.findViewById(R.id.signup);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
On side note, setting up click listener initializing TextView's etc should be done inside onViewCreated(). onCreateView() should just create & return the view.
like
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
TextView signup = (TextView) view.findViewById(R.id.signup);
// and so on...
}
I would recommend not setting a click listener into something you want to type into
You can't call getView before onCreateView has actually returned a proper View
findViewById in Fragment
RegisterFragment.class is not an Activity, you cannot startActivity for it.
Use the FragmentManager
getSupportFragmentManager().beginTransaction()
.replace(R.id.<someContainer>, RegisterFragment.class)
.commit();
Or you can see the documentation on Communication between Fragments to see how you might implement on onLogin() or onRegistrationSelected() action to swap out to the registration fragment or "post-login" main fragment.

Button setOnClickListener onCreateView() or onActivityCreated() in Fragment

by this answer
I can't understand where to put my onClickListener() - inside onCreateView() or inside onActivityCreated() , below codes describe it better:
CODE A: (Setting Button click listener inside onActivityCreated())
private FloatingActionButton bt;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something.
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
bt = (FloatingActionButton) v.findViewById(R.id.fab);
return v;
}
CODE B: (Setting Button click listener inside onCreateView())
private FloatingActionButton bt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
bt = (FloatingActionButton) v.findViewById(R.id.fab);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something.
}
});
return v;
}
I may have not understood which code is better because of my poor English, anyway, thank you all :)
Both will have no effect as far as I know. Once the view is inflated you can put it anywhere either in onCreateView() or in onActivityCreated().
After all, for binding views and setting click listeners, onViewCreated() is a better candidate though, as it will be called immediately after onCreateView. It clearly suggests that your view has been inflated.
There is no specific reason or rule for it. Google itself doesn't care much about it. As a rule of thumb, you can put it anywhere you want once the view is inflated.
I would suggest putting the onClickListener it inside the onActivityCreated. And binding the button to the view inside onCreateView. Just like you have done the first time in your question.
To read more regarding the methods you can go through this post
Since onActivityCreated was deprecated in API level 28, it's probably wise to put it in onCreateView!

Categories

Resources