如何在片段中显示活动元素或视图,以及如何在不从片段移动到活动的情况下从片段进行访问,并且反之亦然。
这是我的问题:-
我在“活动”中使用“搜索编辑框”,我想在片段中使用此搜索框,但是我不想在片段中创建任何搜索框,我只想在“用户类型”时在“片段”中显示此活动搜索框在搜索框中,然后使用textWatcher跟踪文本,并在不在Activity中的片段中显示搜索框的结果。
下面是我要制作的UI图像。
答案 0 :(得分:1)
您可以通过以下方式从片段访问活动元素和方法:
活动模板
public class ActivityMain extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content)
}
public void updateView(){
// update your views & vars here
}
}
片段模板
public class BlankFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_blank, container, false);
}
}
public void updateActivityView(){
if (getActivity() != null){
((ActivityMain) getActivity()).updateView();
}
}
反之亦然,您可以通过以下方式从活动访问片段项目:
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.specific_function_name();
R.id.example_fragment 最可能位于xml布局内的FrameLayout ID