简体   繁体   中英

Is it possible to start Fragment class from an Activity class..Using Intent

I have a MainActivity class,Is it possible to start a fragment class using Button onclicklistner

Main Activity Class:

public class MainActivity extends AppCompatActivity  {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button r_btn=(Button) findViewById(R.id.btn_register);
    r_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(MainActivity.this, test.class);
            startActivity(i);
        }
    });

Fragment Class

public class test extends Fragment{

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_test, container, false);
    rootView.findViewById(R.id.label1);

    // Inflate the layout for this fragment
    return rootView;
    }
}

Any tips would be helpful..

Yes you can but you cant treat fragment like activity so you cant use startActivity method. Use fragment manager to call fragment

 fragmentContainer = (RelativeLayout) findViewById(R.id.fragmentContainer);

  r_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           replaceFragmentInContainer(new test(), fragmentContainer.getId(), getSupportFragmentManager());
        }
    });



 public void replaceFragmentInContainer(Fragment DestinationFragment,int containerResourceID,FragmentManager fragmentManager )
    {
        FragmentTransaction ft=fragmentManager.beginTransaction();
        int viewResourceID = containerResourceID;
        ft.replace(viewResourceID, DestinationFragment);
        ft.commit();
    }

Your container in activity xml that will handle your fragment

 <RelativeLayout
            android:id="@+id/fragmentContainer"
            android:layout_width="match_parent"
            android:layout_below="@+id/toolbar"
            android:layout_height="match_parent"
            >
        </RelativeLayout> 

or you can check this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM