fragment的单独使用

布局:

1.使用FrameLayout当做占位

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="@+id/tv1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="第一个fragment"
/>
<TextView
android:id="@+id/tv2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="第二个fragment"
/>
</LinearLayout>

<FrameLayout
android:id="@+id/fl"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>

代码:

1)fragment的代码:

public class Fragment1 extends Fragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
    View view=View.inflate(getActivity(), R.layout.page, null);
    TextView tv=(TextView) view.findViewById(R.id.textView1);
    tv.setText("这是第一个fragment");
    return view;
  }

}

 

2)MainActivity的代码:

public class MainActivity extends FragmentActivity implements OnClickListener{

private FragmentManager manager;
private Fragment1 f1;
private Fragment2 f2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//寻找控件
  TextView tv1=(TextView) findViewById(R.id.tv1);
  TextView tv2=(TextView) findViewById(R.id.tv2);
  f1 = new Fragment1();
  f2 = new Fragment2();
  manager = getSupportFragmentManager();
  FragmentTransaction transaction = manager.beginTransaction();
  transaction.add(R.id.fl, f1, "f1");
  transaction.add(R.id.fl, f2, "f2");

  //一起提交
  transaction.commit();

  tv1.setOnClickListener(this);
  tv2.setOnClickListener(this);
  changePage(R.id.tv1);
}

 

  @Override
  public void onClick(View v) {
  changePage(v.getId());
  }

 

  private void changePage(int id) {
  FragmentTransaction transaction = manager.beginTransaction();

  switch (id) {
  case R.id.tv1:

  transaction.show(f1);
  transaction.hide(f2);

  break;
  case R.id.tv2:

  transaction.show(f2);
  transaction.hide(f1);

  break;

  }

  transaction.commit();
}



}

转载于:https://www.cnblogs.com/coins1/p/5382157.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值