使用Fragment时如何获取控件Id以及如何跳转

如题所述

第1个回答  2018-07-25
一、使用Fragment获取控件Id
我是在MainActivity中通过Fragment的事务管理把各个fragment添加到MainActivity中的,但是MainActivity中并没有很多控件,控件大都在各个fragment的布局里面,所以如何在fragmen中获取控件Id是一件非常重要的事!话不多说直接上代码!
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View messageLayout=inflater.inflate(R.layout.message_layout,container,false); inspect= (TextView) messageLayout.findViewById(R.id.inspect); inspect.setOnClickListener(new View.OnClickListener() {

在OncreatView方法中,先是通过View方法把布局加载到fragmnet中,然后在使用加载的布局中的findViewById的方法找到控件,这和之前的用法是不一样的,之前是直接findViewById。
二、如何在fragment中跳转Activity
话不多话,直接上代码!
Intent intent=new Intent(getActivity(),InspectActivity.class);startActivity(intent);

与平常跳转不同的地方在于这里是:
new Intent(getActivity(),InspectActivity.class);本回答被网友采纳