如何使用EditText在片段和活动之间传递信息



好吧,我目前正在做一个学校项目,我的应用程序在第一个和第二个选项卡中有三个选项卡,它有两个不同的网页视图,网页显示正确,在第三个选项卡中,它有二个EditText供我更改这些网页。当我试图从片段中找到这些EditText并保存url时,问题就来了。我怎么能把它做好呢?

public class WebpageSetter_Fragment extends Fragment {
EditText direccion1, direccion2;
Button cambiarUrl;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.set_webpage_fragment, container, false);
}

使用此代码

EditText direccion1, direccion2;
Button cambiarUrl;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.set_webpage_fragment,container,false);
direccion2 = view.findViewById(R.id.your_edittext_id);
//same for the other edittext
//If you have a button to get the text and set the website into webviews,then find the button ID in same way and then use setOnClickListener on the button and then do the stuff
return view;
}

这适用于你想在任何地方找到的任何类型的视图,如果在某种容器中有一个视图,例如,考虑LinearLayout,你可以使用相同的方法在LinearLayout中找到视图,初始化LinearLayout,然后使用

linearLayoutObject.findViewById(R.id.id_of_view_you_want_to_find);

在父活动中生成方法,并将数据从片段传递到活动,然后将数据从父活动获取到任何片段,在您的情况下,每个片段都是同一父活动的子片段。

最新更新