美文网首页
Android Fragment —— 1、基础实例

Android Fragment —— 1、基础实例

作者: 消极程序员 | 来源:发表于2017-04-20 15:05 被阅读0次

一、Fragment的产生与介绍
Android运行在各种各样的设备中,有小屏幕的手机,超大屏的平板甚至电视。针对屏幕尺寸的差距,很多情况下,都是先针对手机开发一套App,然后拷贝一份,修改布局以适应平板神马超级大屏的。难道无法做到一个App可以同时适应手机和平板么,当然了,必须有啊。Fragment的出现就是为了解决这样的问题。你可以把Fragment当成Activity的一个界面的一个组成部分,甚至Activity的界面可以完全有不同的Fragment组成,更帅气的是Fragment拥有自己的生命周期和接收、处理用户的事件,这样就不必在Activity写一堆控件的事件处理的代码了。更为重要的是,你可以动态的添加、替换和移除某个Fragment。

二、Fragment实例
1、创建Fragment

public class TestStripsFragment extends Fragment implements View.OnClickListener{

    private Button button;

    //重点在此,Fragment通过onCreateView来引用布局文件,其与activity用法一致
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_content, container, false);
        button = (Button) view.findViewById(R.id.bt);
        button.setOnClickListener(this);

        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt:
                Toast.makeText(getActivity(),"wzzoooooooooo",Toast.LENGTH_SHORT).show();
            break;
        }
    }
}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <Button
        android:id="@+id/bt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="click"/>

</RelativeLayout>

2、在MainActivity中引用Fragment,此例中是直接在布局文件中引用的

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="wzz.a2017wzzteststrips.MainActivity">

    //重点,在此将Fragment引入MainActivity
    <fragment
        android:id="@+id/id_fragment_content"
        android:name="wzz.a2017wzzteststrips.TestStripsFragment"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</RelativeLayout>

MainActivity代码:

public class MainActivity extends Activity {

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

到此为止,一个简单的Android Fragment应用就创建完成了,之后相关的逻辑操作都放在Fragment类中进行就可以了。

相关文章

网友评论

      本文标题:Android Fragment —— 1、基础实例

      本文链接:https://www.haomeiwen.com/subject/farlzttx.html