扣丁学堂——Fragments

一丶源码见本文

二丶课程讲解

扣丁学堂——Fragments_第1张图片

扣丁学堂——Fragments_第2张图片

扣丁学堂——Fragments_第3张图片

扣丁学堂——Fragments_第4张图片


扣丁学堂——Fragments_第5张图片

方法一:布局文件添加(用得多一些)

1.添加布局文件

两个Fragement,注意layout_weight和name属性

<fragment
    android:layout_width="0dip"
    android:layout_height="match_parent"
    android:id="@+id/title_fragment"
    android:layout_weight="1"
    android:name="com.jin.administrator.my1220application.TitleFragment"/>
<fragment
    android:layout_width="0dip"
    android:layout_height="match_parent"
    android:layout_weight="3"
    android:name="com.jin.administrator.my1220application.ContentFragment"
    android:id="@+id/content_fragment"
    />
这里name分别对应的是相应的fragement的class

public class ContentFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content_layout, container, false);
        return view;
    }
}
public class TitleFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.title_layout,container,false);
        return view;
    }
}
而每一个class对应一个布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#00ff00">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="时间"
        android:id="@+id/button" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="地点"
        android:id="@+id/button2" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="人物"
        android:id="@+id/button3" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="#00ddff">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="571dp"
        android:text="没有数据"
        android:gravity="center"
        android:id="@+id/textView" />
</LinearLayout>

MainActivity,主要将Fragement放入:

public class MainActivity extends AppCompatActivity {
    TitleFragment titleFragment;
   ContentFragment contentFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //通过 getFragmentManager(管理器获取fragment来获取实例)
        titleFragment = (TitleFragment) getFragmentManager().findFragmentById(R.id.title_fragment);
        contentFragment = (ContentFragment) getFragmentManager().findFragmentById(R.id.content_fragment);
        }
}

演示效果:

方法二:代码添加

看一下MainActivity就行

public class MainActivity2Activity extends Activity {
    ContentFragment contentFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity2);

        addContentLayout();

    }
    /***
     *
     * 通过代码添加Fragment
     *
     * @param
     */
    private  void addContentLayout(){
        FragmentManager fm = getFragmentManager();
        //开启一个事务
        FragmentTransaction ft = fm.beginTransaction();
//创建fragment实例对象
        contentFragment = new ContentFragment();
        //添加fragment到指定布局的中中显示
        ft.add(R.id.content_layout,contentFragment);
        //ft.remove(); 删除
        //ft.replace(); 替换
        Log.i("Layout","添加frament");
        ft.commit();//提交事务
    }
}

扣丁学堂——Fragments_第6张图片

新建一个Activity

布局文件:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="one"
        android:id="@+id/button4"
        android:layout_below="@+id/textView2"
        android:layout_alignParentStart="true"
        android:onClick="oneClick"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="two"
        android:id="@+id/button5"
        android:layout_below="@+id/textView2"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="25dp"
        android:onClick="twoClick"
        />
    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/button4"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:id="@+id/content"
      ></FrameLayout>

Activity.mian

public class PopBackTaskActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pop_back_task);
    }

//当单击的时候显示不同的fragment内容
    public void oneClick(View v){
        PopBackFragment p1 = new PopBackFragment("two");
       FragmentTransaction ft =  getFragmentManager().beginTransaction();
        ft.replace(R.id.content,p1);
        //把当前fragment添加到Activity栈中
        ft.addToBackStack(null);
        ft.commit();
    }

    public  void  twoClick(View v){
        PopBackFragment p2 = new PopBackFragment("one");//创建fragment类

//开启事务
        FragmentTransaction ft =  getFragmentManager().beginTransaction();

//替换activity中的组件,
//参数:要替换的id, fragment组件(这里通过代码的方式来添加fragment组件)
        ft.replace(R.id.content,p2);

        //把当前fragment添加到Activity栈中
        ft.addToBackStack(null);

        ft.commit();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(getFragmentManager().getBackStackEntryCount() == 0){
                finish();
            }else {
                getFragmentManager().popBackStack();//出栈的动作
            }
           return  true;

        }
        return super.onKeyDown(keyCode,event);

    }
}

鼠标右键创建一个空白frament,会自动生成继承fragment类和xml文件

public class PopBackFragment extends Fragment {

    String title;

    public PopBackFragment() {

    }

    public PopBackFragment(String title){//传入字符,用于区分不同的显示
        this.title = title;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view =  inflater.inflate(R.layout.fragment_pop_back, container, false);

//获取布局中的textView组件
         TextView tx = (TextView) view.findViewById(R.id.textViw_text);

//设置字符串
        tx.setText(title);
        return view;
    }
}
这里演示的效果就是,显示两Fragement的切换退栈效果,因为加了onKeyDowm,按返回也是退栈效果


优化上面的方法:原因:fragment传参问题,上面的结果导致手机屏幕旋转时,frangment会丢失传入的参数

public class PopBackFragment extends Fragment {

    public PopBackFragment() {

    }
    //正确的给 fragment传递参数
    public static PopBackFragment getInstance(String title){
        PopBackFragment p = new PopBackFragment();

        Bundle bundle = new Bundle();
        bundle.putString("title",title);

        p.setArguments(bundle);//保存传入的参数

        return  p;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_pop_back, container, false);

         TextView tx = (TextView) view.findViewById(R.id.textViw_text);

        tx.setText(getArguments().getString("title"));
        return view;
    }
}


public class PopBackTaskActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pop_back_task);
    }

    public void oneClick(View v){

        PopBackFragment p1 =PopBackFragment.getInstance("one");

       FragmentTransaction ft =  getFragmentManager().beginTransaction();

        ft.replace(R.id.content,p1);

        //把当前fragment添加到Activity栈中
        ft.addToBackStack(null);

        ft.commit();

    }


    public  void  twoClick(View v){

        PopBackFragment p2 = PopBackFragment.getInstance("two");

        FragmentTransaction ft =  getFragmentManager().beginTransaction();
        ft.replace(R.id.content,p2);

        //把当前fragment添加到Activity栈中
        ft.addToBackStack(null);

        ft.commit();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(getFragmentManager().getBackStackEntryCount() == 0){
                finish();
            }else {
                getFragmentManager().popBackStack();//出栈的动作
            }
           return  true;
        }
        return super.onKeyDown(keyCode,event);
    }
}


扣丁学堂——Fragments_第7张图片

//fragment与activity之间的交互

1.创建两个 fragment
<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="新闻"
        android:id="@+id/button1"

        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="音乐"
        android:id="@+id/button2"
        android:layout_gravity="left|top"

        />

-------------------------
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/value"

        android:text="no data"

        android:layout_gravity="center"
        />

----fragment事件源中创建一个回调接口,得到activity并调用实现接口的方法-------

public class MainFragment extends Fragment implements View.OnClickListener {

    private  MainLister mainLister;


    public MainFragment() {
        // Required empty public constructor
    }


    //获取activity,也就是宿主
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mainLister = (MainLister) activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View V =  inflater.inflate(R.layout.fragment_main, container, false);

        V.findViewById(R.id.button1).setOnClickListener(this);
        V.findViewById(R.id.button2).setOnClickListener(this);

        return V;
    }


    //单击按钮更新另一个fragment中的值,fragment之间产生交互
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button1:
                mainLister.changeValue("news");
            break;
            case R.id.button2:
                mainLister.changeValue("music");
            break;
        }
    }


    //定义一个回调接口
    public static interface MainLister{
        public void changeValue(String value);
    }
}
------要改变的fragmen---------
public class MentFragment extends Fragment {

    private TextView textView_value;

    public MentFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v =  inflater.inflate(R.layout.fragment_ment, container, false);

        textView_value= (TextView) v.findViewById(R.id.value);

        return v;

    }

    public  void changeTextValue(String value){
        textView_value.setText(value);
    }

}

---------activity,并实现接口------------

public class MainActivity extends ActionBarActivity implements MainFragment.MainLister {

    private MentFragment mentFragment;
    private MainFragment mainFragment;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取两个fragment对象
        mainFragment = (MainFragment) getFragmentManager().findFragmentById(R.id.main);
        mentFragment = (MentFragment) getFragmentManager().findFragmentById(R.id.ment);
    }



    @Override
    public void changeValue(String value) {
        mentFragment.changeTextValue(value);
    }
}

扣丁学堂——Fragments_第8张图片

1.preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
        android:title="打开声音">
        <CheckBoxPreference
            android:key="checkbox_preference"
            android:title="打开"
            android:summary="声音设置" />
    </PreferenceCategory>
    <PreferenceCategory
        android:title="城市">
        <EditTextPreference
            android:key="edittext_preference"
            android:title="城市名称"
            android:summary="请输入城市"
            android:dialogTitle="城市标题" />
      <ListPreference
            android:key="list_preference"
            android:title="城市名称1"
            android:summary="请选择城市名称"
            android:entries="@array/city"
            android:entryValues="@array/city"
            android:dialogTitle="城市名称" />
    </PreferenceCategory>
</PreferenceScreen>
string.xml

<string-array name="city">
    <item>北京</item>
    <item>上海</item>
    <item>武汉</item>
    <item>深圳</item>
</string-array>
mainActivity

public class Main2Activity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        SharedPreferences sp =  PreferenceManager.getDefaultSharedPreferences(this);
        String name  =  sp.getString("checkbox_preference","");
        Log.i("msg", name);
    }
}
main布局

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/perfs_fragment"
    android:name="com.jin.administrator.my1220application.PreFragment"
    ></fragment>
定义一个fragment

public class PreFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载Preferences.xml文件
        addPreferencesFromResource(R.xml.preference);
    }
}
演示效果:


你可能感兴趣的:(扣丁学堂,Fragement)