fragment的基本用法

来源:互联网 发布:跟章泽天是校友 知乎 编辑:程序博客网 时间:2024/05/22 10:26

1.首先创建一个UI线程

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {    private HomeFragment mHomeFragment;    private DmFragment mDmFragment;    private SearchFragment mSearchFragment;    private PersonalFragment mPersonalFragment;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //主流的 底部tab切换页面的设计        RadioGroup group = (RadioGroup)findViewById(R.id.main_tab_bar);        FragmentManager manager = getSupportFragmentManager();        Fragment f = manager.findFragmentByTag("home");        if (group != null) {            group.setOnCheckedChangeListener(this);        }        // 1.创建所有的Fragment对象 便于切换的是时候使用        if (f == null){            mHomeFragment = new HomeFragment();        }else{            mHomeFragment = (HomeFragment) f;        }        f = manager.findFragmentByTag("dm");        if (f == null){            mDmFragment = new DmFragment();        }else {            mDmFragment = (DmFragment) f;        }        f = manager.findFragmentByTag("search");        if (f == null){            mSearchFragment = new SearchFragment();        }else{            mSearchFragment = (SearchFragment) f;        }        f = manager.findFragmentByTag("personal");        if (f == null){            mPersonalFragment = new PersonalFragment();        }else{            mPersonalFragment = (PersonalFragment) f;        }        //2.每一个Fragment 可以通过两种方式添加到activity        // 1)使用<Fragment> 标签添加        // 2)使用代码来添加Fragment//        FragmentManager manager = getSupportFragmentManager();//        FragmentTransaction tx = manager.beginTransaction();////        tx.add(R.id.fragment_container,mHomeFragment);//        tx.commit();        //使用默认的方式        group.check(R.id.main_tab_home);    }    public void bntJumpNext(View view) {        Intent intent = new Intent(this, SeconedActivity.class);        startActivity(intent);    }    @Override    public void onCheckedChanged(RadioGroup group, int checkedId) {        FragmentManager manager = getSupportFragmentManager();        FragmentTransaction tx = manager.beginTransaction();        switch (checkedId) {            case R.id.main_tab_home://                tx.replace(R.id.fragment_container,mHomeFragment);                tx.replace(R.id.fragment_container,mHomeFragment,"home");                break;            case R.id.main_tab_dm://                tx.replace(R.id.fragment_container,mDmFragment);                tx.replace(R.id.fragment_container,mDmFragment,"dm");                break;            case R.id.main_tab_search:                tx.replace(R.id.fragment_container,mSearchFragment,"search");                break;            case R.id.main_tab_personal:                tx.replace(R.id.fragment_container,mPersonalFragment,"personal");                break;        }        tx.commit();    }}
2) 该UI线程的布局文件

<?xml version="1.0" encoding="utf-8"?><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:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:orientation="vertical"    tools:context="com.wwj_fly.myfragment.MainActivity">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Hello World!"/>    <fragment        class="com.wwj_fly.myfragment.fragments.TimeFragment"        android:id="@+id/fragment_time_0"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        />    <fragment        class="com.wwj_fly.myfragment.fragments.TimeFragment"        android:id="@+id/fragment_time_1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="bntJumpNext"        />    <!--使用FrameLayout 来显示 Fragment-->    <FrameLayout        android:id="@+id/fragment_container"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1"></FrameLayout>    <!--通常tab 样式的切换-->    <RadioGroup        android:id="@+id/main_tab_bar"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">       <RadioButton           android:id="@+id/main_tab_home"           android:layout_width="0dp"           android:layout_weight="1"           android:text="首页"           android:layout_height="wrap_content"/>        <RadioButton            android:id="@+id/main_tab_dm"           android:layout_width="0dp"           android:layout_weight="1"           android:text="私信"           android:layout_height="wrap_content"/>        <RadioButton            android:id="@+id/main_tab_search"            android:layout_width="0dp"            android:layout_weight="1"            android:text="搜索"            android:layout_height="wrap_content"/>        <RadioButton            android:id="@+id/main_tab_personal"            android:layout_width="0dp"            android:layout_weight="1"            android:text="我的"            android:layout_height="wrap_content"/>    </RadioGroup></LinearLayout>
2.创建fragment

/** Fragment 的创建步骤:** 1.继承 Fragment v4 包的* 2.必须有且仅有一个无参的构造方法* 3.如果fragment需要显示界面的话 需要重写 onCreateView方法* 4.制定布局资源 或者创建布局 返回即可* */public class TimeFragment extends Fragment implements Runnable{    private TextView mTextDate;    private TextView mTextTime;    private Handler mHandler = new Handler(){        @Override        public void handleMessage(Message msg) {            //message内部的what            // 假定 998 是设置日期的            String str = (String) msg.obj;            switch (msg.what) {                case 998:                    mTextDate.setText(str);                    break;                case 999:                    mTextTime.setText(str);                    break;            }        }    };    public TimeFragment() {    }    // 返回 Fragment的界面部分 和Adapter的getView 方法类似    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View ret = inflater.inflate(R.layout.time_fragment, container, false);        // 在 onCreateView内部 可以设置控件的内容 开启线程 连接网络        mTextDate = (TextView)ret.findViewById(R.id.txt_date);        mTextTime = (TextView) ret.findViewById(R.id.txt_time);        Date date = new Date();        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");        mTextDate.setText(format.format(date));        format.applyPattern("HH:mm:ss");        mTextTime.setText(format.format(date));        //启动一个线程        Thread thread = new Thread(this);        thread.start();        return ret;    }    @Override    public void run() {        try{            Calendar calendar = Calendar.getInstance();            StringBuilder sb = new StringBuilder();            while(true){                calendar.setTimeInMillis(System.currentTimeMillis());                int year = calendar.get(Calendar.YEAR);                int month = calendar.get(Calendar.MONTH);                int date = calendar.get(Calendar.DATE);                int hour = calendar.get(Calendar.HOUR_OF_DAY);                int min = calendar.get(Calendar.MINUTE);                int sec = calendar.get(Calendar.SECOND);                sb.append(year).append('-').append(month + 1)                        .append('-').append(date);                String str = sb.toString();                Message message = mHandler.obtainMessage(998);                message.obj = str;                //子线程需要通过Handler 给主线程发送消息                mHandler.sendMessage(message);                // 时间的部分                sb.setLength(0);                sb.append(hour).append(':').append(min).append(':').append(sec);                str = sb.toString();                message = mHandler.obtainMessage(999);                message.obj = str;                mHandler.sendMessage(message);                sb.setLength(0);                Thread.sleep(1000);            }        }catch (InterruptedException ex){            ex.printStackTrace();        }    }}

2)对应的布局文件

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:layout_width="match_parent"              android:layout_height="match_parent">    <TextView        android:id="@+id/txt_date"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="2016-09-13"        />    <TextView        android:id="@+id/txt_time"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="10:00:00"/></LinearLayout>




0 0
原创粉丝点击