fragment事物跳转

来源:互联网 发布:淘宝工作室怎么运营 编辑:程序博客网 时间:2024/06/11 18:33
package com.bwei.czx.czx;import android.graphics.Color;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.FrameLayout;import com.bwei.czx.fragment.FragmentLawyer;import com.bwei.czx.fragment.FragmentWeather;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private Button fondLawyer;    private Button weather;    private FrameLayout frameLayout;    private FragmentManager fm;    private List<Button> buttonList;    private List<Fragment> fragments;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //找到按钮控件        fondLawyer = (Button) findViewById(R.id.fondLawyer);        weather = (Button) findViewById(R.id.weather);        weather.setOnClickListener(this);        fondLawyer.setOnClickListener(this);        //点击按钮添加到集合        buttonList = new ArrayList<>();        buttonList.add(weather);        buttonList.add(fondLawyer);        //找到fragment控件        frameLayout = (FrameLayout) findViewById(R.id.frameLayout);        //添加fragment布局        fragments = new ArrayList<>();        FragmentLawyer fragmentLawyer = new FragmentLawyer();        FragmentWeather fragmentWeather = new FragmentWeather();        fragments.add(fragmentWeather);        fragments.add(fragmentLawyer);        //得到事务管理器        fm = getSupportFragmentManager();        //开启事务        FragmentTransaction ft = fm.beginTransaction();        //把fragment添加到FragmentLayout里面        ft.add(R.id.frameLayout,fragmentWeather);        ft.add(R.id.frameLayout,fragmentLawyer);        ft.hide(fragmentLawyer);        //提交事务        ft.commit();    }    @Override    public void onClick(View v) {        //实现点击按钮,页面跳转联动效果        //开启事务        FragmentTransaction ft = fm.beginTransaction();        for (int i = 0;i < buttonList.size();i++){            //得到按钮            Button button = buttonList.get(i);            if(button.getId() == v.getId()){                button.setBackgroundColor(Color.RED);                ft.show(fragments.get(i));            }else{                button.setBackgroundColor(Color.GRAY);                ft.hide(fragments.get(i));            }        }        //提交事务        ft.commit();    }}

原创粉丝点击