[练习-1] android studio 从Activity 进入 Fragment

时间:2021-06-08 15:51:15

从activity 进入到 fragment,使用系统自带的ListFragment

1,新建empty activity

2,新建Fragment(List)

3,activity_main.xml 修改为framlayout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>

4,在MainActivity.java 修改,新增见红色

public class MainActivity extends AppCompatActivity implements ItemFragment.OnListFragmentInteractionListener{

    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
      
     // 新增传递ItemFrament
ItemFragment f = ItemFragment.newInstance (1);
getSupportFragmentManager().beginTransaction().add(R.id.fragment, f).commit();
}

   // 实现接口
@Override
public void onListFragmentInteraction(DummyContent.DummyItem item) {
}

5,实现效果

[练习-1] android studio 从Activity 进入 Fragment