是否可以从片段

时间:2016-07-09 23:35:00

标签: java android-studio android-fragments

我相信答案是肯定的..不确定FragmentManager是否适用于此...因为一个片段包含一个ListView而另一个片段包含不同的小部件(ImageView,Text)

在我的主要活动中,我使用以下方式调用我的第一个片段:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    LFragment lFragment=    (LFragment)getSupportFragmentManager().findFragmentByTag("lFragment");
    if(lFragment==null){
        lFragment= new LFragment();
        FragmentTransaction  transaction=getSupportFragmentManager().beginTransaction();
        transaction.add(android.R.id.content,lFragment,"lFragment");
        transaction.commit();
    }

好的,所以一旦我进入我的LFragment(1st Fragment)课程,我就会使用这种方法转到下一个片段:

//handling item click
public void onListItemClick(ListView l, View view, int position, long id){
    ViewGroup viewGroup=(ViewGroup)view;
    TextView txt=(TextView)viewGroup.findViewById(R.id.txtitem);
    int itemPosition = position;
    //stores the text of the clicked item in the list
    String value = (String) l.getItemAtPosition(position);
    //using intent to get into infoFragment
    Intent intent = new Intent(view.getContext(),infoFragment.class);
    //store string value into intent
    intent.putExtra(value,itemPosition);

    view.getContext().startActivity(intent);
    //kills the fragment
    getActivity().finish();

这是我尝试使用的(第二片段)..但getIntent不起作用

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.info_layout, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState){
    ImageView image = (ImageView) view.findViewById(R.id.imageView);
    RatingBar rating=(RatingBar) view.findViewById(R.id.ratingBar);
    TextView degrees=(TextView)view.findViewById(R.id.textView);
    //ERROR "can not resolve method getIntent"
    Intent intent = getIntent();
}

1 个答案:

答案 0 :(得分:0)

试试这个...

LFragment fragment = new LFragment();
FragmentManager FM = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction =  FM.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();