在android中如何从片段调用活动

在android中如何从片段调用活动,android,android-activity,fragment,Android,Android Activity,Fragment,我有两个班 ProfileFragment.class public class ProfileFragment extends Fragment implements OnClickListener { Fragment fragment = null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedI

我有两个班

ProfileFragment.class

public class ProfileFragment extends Fragment implements OnClickListener {

    Fragment fragment = null;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_profile, container,false);
        return rootView;
    }
}
public class LastCheckins extends Activity {    

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScrollView sv = (ScrollView) findViewById(R.id.scrollView1);
        LinearLayout ll = (LinearLayout) findViewById(R.id.LinearLayout1);
        ll.setOrientation(LinearLayout.VERTICAL);
        sv.addView(ll);
        for (int i = 0; i < 20; i++) {
            CheckBox cb = new CheckBox(this);
            cb.setText("I'm dynamic!");
            ll.addView(cb);
        }
        this.setContentView(sv);
    }
}
LastCheckins.class

public class ProfileFragment extends Fragment implements OnClickListener {

    Fragment fragment = null;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_profile, container,false);
        return rootView;
    }
}
public class LastCheckins extends Activity {    

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScrollView sv = (ScrollView) findViewById(R.id.scrollView1);
        LinearLayout ll = (LinearLayout) findViewById(R.id.LinearLayout1);
        ll.setOrientation(LinearLayout.VERTICAL);
        sv.addView(ll);
        for (int i = 0; i < 20; i++) {
            CheckBox cb = new CheckBox(this);
            cb.setText("I'm dynamic!");
            ll.addView(cb);
        }
        this.setContentView(sv);
    }
}
公共类LastCheckins扩展活动{
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
ScrollView sv=(ScrollView)findViewById(R.id.scrollView1);
LinearLayout ll=(LinearLayout)findViewById(R.id.LinearLayout1);
ll.设置方向(线性布局、垂直);
sv.addView(ll);
对于(int i=0;i<20;i++){
复选框cb=新复选框(此复选框);
cb.setText(“我是动态的!”);
ll.addView(cb);
}
这个.setContentView(sv);
}
}
当程序创建ProfileFragment类时,如何调用Activity类

非常感谢

getActivity()
返回此片段当前关联的活动。

使用getActivity()

您可以将其强制转换为LastChekins,以便调用其metods并访问其可见字段:

((LastCheckins)getActivity()).methodX();

这是错误的<如果没有要查找的视图,code>findViewById将始终返回。除非您在活动中自己创建片段,否则不会创建该片段。您应该使用布局文件,然后使用
setContentView
将其充气。