项目中经常会用到fragment,写了个简单的demo
Activity
public class MainActivity extends FragmentActivity implements OnClickListener {
private FrameLayout frame;
private LinearLayout layout_car;
private LinearLayout layout_home;
private ImageButton car;
private ImageButton home;
private Fragment tab1;
private Fragment tab2;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main_activity);
initView();
eventView();
seletor(0);
}
private void initView() {
layout_car = (LinearLayout) findViewById(R.id.layout_car);
layout_home = (LinearLayout) findViewById(R.id.layout_home);
car = (ImageButton) findViewById(R.id.car);
home = (ImageButton) findViewById(R.id.home);
}
private void eventView() {
layout_car.setOnClickListener(this);
layout_home.setOnClickListener(this);
}
@Override
public void onClick(View v) {
resetImg();
switch (v.getId()) {
case R.id.layout_car:
seletor(0);
break;
case R.id.layout_home:
seletor(1);
break;
default:
break;
}
}
private void seletor(int i) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
hideFragment(transaction);
switch (i) {
case 0:
if (tab1 == null) {
tab1 = new CarFragment();
transaction.add(R.id.frame, tab1);
}else{
transaction.show(tab1);
}
car.setImageResource(R.drawable.n_distribution_l);
break;
case 1:
if (tab2 == null) {
tab2 = new HomeFragment();
transaction.add(R.id.frame, tab2);
}else{
transaction.show(tab2);
}
home.setImageResource(R.drawable.n_home_l);
break;
default:
break;
}
transaction.commit();
}
private void hideFragment(FragmentTransaction transaction) {
if (tab1 !=null) {
transaction.hide(tab1);
}
if (tab2 !=null) {
transaction.hide(tab2);
}
}
private void resetImg() {
car.setImageResource(R.drawable.n_distribution_h);
home.setImageResource(R.drawable.n_home_h);
}
}
使用FragmentTransaction的show/hide来显示/隐藏fragment,不会销毁fragment实例,fragment跳转切换数据不重新加载
Fragment
public class CarFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.car, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initView(view);
addListener();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
main_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<include layout="@layout/top"/>
<FrameLayout
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
>
</FrameLayout>
<include layout="@layout/bottom"/>
</LinearLayout>
top和bottom分别是顶部标题和底部标签切换fragment控件