Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android pass View as an object to fragment

I'm more googling to find how can i pass simple view as an object to fragment, but i can't.

for example in MainActivity i have simple view as :

TextView text = (TextView) findviewById(R.id.tv_text);

now i want to pass that to fragment. this below code is my attach Fragment on MainActivity

MainActivity :

public void attachFragment() {
    fts = getActivity().getFragmentManager().beginTransaction();
    mFragment = new FragmentMarketDetail();
    fts.replace(R.id.cardsLine, mFragment, "FragmentMarketDetail");
    fts.commit();
}

and this is my Fragment:

public class FragmentMarketDetail extends Fragment implements ObservableScrollViewCallbacks {
    public static final String SCROLLVIEW_STATE = "scrollviewState";
    private ObservableScrollView scrollViewTest;
    private Context    context;
    private int scrollY;

    public static FragmentMarketDetail newInstance() {
        FragmentMarketDetail fragmentFirst = new FragmentMarketDetail();
        return fragmentFirst;
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_online_categories, container, false);
        scrollViewTest = (ObservableScrollView) view.findViewById(R.id.scrollViewTest);
        scrollViewTest.setScrollViewCallbacks(this);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity().getBaseContext();
    }
}
like image 903
DolDurma Avatar asked Jul 01 '16 11:07

DolDurma


1 Answers

It wouldn't be good practise to pass a view that way. If you want to access the view in your activity from within your fragment class, use getActivity() to access the activity to which your fragment is attached, and from there you find your TextView.

TextView text = (TextView) getActivity().findViewById(R.id.tv_text);
like image 69
Karen Forde Avatar answered Oct 10 '22 08:10

Karen Forde