Get view of Fragment from FragmentActivity

。_饼干妹妹 提交于 2019-11-30 10:53:52
Jarvis

If you want to access your component and set some data, I suggest you to make a method inside the fragment like this:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class DetailFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.details, container, false);
        return view;
    }


    public void setSettings(){
        Button button = (Button) getView().findViewById(R.id.my_button);
        button.setOnClickListener(new MyClickListener());
    }
}

try this:

public class YourFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          return inflater.inflate(R.layout.your_fragment, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        View view = getView();
        if(view != null) {
            view.findViewById(R.id.my_button).setOnClickListener(new MyClickListener());
        }
    }
}

this code must works fine. I hope, this will help you.

JB0x2D1

To set OnClickListeners in fragments, override onViewCreated in your fragment class.

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    view.findViewById(R.id.yourId).setOnClickListener(this);
    //or
    getActivity().findViewById(R.id.yourId).setOnClickListener(this);
}

I was trying to set a timertask to automatically reload a webview in a fragment and this method was the only thing that worked for me. My project is on github.

Source: this answer

Alex P

When you initialize your button inside a class that extends Fragment it's better to do it inside the onViewCreated() method. This will guarantee that the view already exists.

Simply Use the getRootView() method to get the data of your fragment in Activity.

//below block of code write in activity.

EditText et = (EditText) v.getRootView().findViewById(R.id.name);
Log.d("Name", et.getText().toString());

name is the field of fragment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!