Fragmen静态加载

来源:互联网 发布:mac usb安装win7 编辑:程序博客网 时间:2024/06/06 06:55
#### 1.静态加载

----1.创建fragment布局文件(second界面的布局)

<?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:layout_width="match_parent"    android:layout_height="50dp"    android:id="@+id/text"    android:textSize="20dp"    />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="改变"        android:textSize="50dp"        android:id="@+id/change"/></LinearLayout>


----2.创建MyFragment对象继承Fragement(加载布局文件fragment及second)

package com.example.asus.fragment;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;//  第二步 继承Fragmentpublic class MyFragment extends Fragment {    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.second, container, false);        TextView textView = (TextView) view.findViewById(R.id.text);        textView.setText("对你越爱越深就越来越心痛");        textView.setTextSize(20);        return view;    }}



----3.然后打开或新建fragment作为主SecondActivity的布局文件,在里面加入Fragment的引用  <fragment> 将MyFragment与其绑定

<?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">    // 第三步 创建布局文件在里面加入两个Fragment的引用    //使用android:name前缀来引用具体的Fragment<fragment    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:id="@+id/fragment"    android:name="com.example.asus.fragment.MyFragment"    >    </fragment></LinearLayout>



----4.在MainActivity中加载主界面(activity_main)

package com.example.asus.fragment;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;/** * Created by ASUS on 2017/5/21. */public class SecondActivity extends Activity {    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.fragment);                   //  这是最后一步        Button button = (Button) findViewById(R.id.change);        final TextView textView = (TextView) findViewById(R.id.text);        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                textView.setText("遥远的她");                textView.setTextSize(20);            }        });    }}



原创粉丝点击