我正在谷歌上搜索如何将简单的 view
作为对象传递给 fragment ,但我做不到。
例如在 MainActivity 中我有一个简单的 View :
TextView text = (TextView) findviewById(R.id.tv_text);
现在我想将其传递给 fragment 。下面的代码是我在 MainActivity 上的附加 fragment
主 Activity
:
public void attachFragment() {
fts = getActivity().getFragmentManager().beginTransaction();
mFragment = new FragmentMarketDetail();
fts.replace(R.id.cardsLine, mFragment, "FragmentMarketDetail");
fts.commit();
}
这是我的 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();
}
}
最佳答案
以这种方式传递 View 不是好的做法。如果您想从 fragment 类中访问 Activity 中的 View ,请使用 getActivity()
访问 fragment 所附加的 Activity ,然后从那里找到您的 TextView。
TextView text = (TextView) getActivity().findViewById(R.id.tv_text);
关于Android 将 View 作为对象传递给 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38143950/