您的位置:首页 > 移动开发 > Android开发

Adroid中Fragment的简单使用

2016-07-15 17:12 399 查看
下面四个步骤就能创建一个简单的fragment
1. 扩展Fragment class
2. 在XML 或 Java中提供显示
3. 覆盖onCreateView方法
4. 在activity中使用Fragment

如下就是简单的显例
创建一个FirstActivityFragment.java文件,扩展Fragment class
package com.example.liang.login;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.VelocityTrackerCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

/**
* Created by liang on 2016/7/15.
*/
public class FirstActivityFragment extends Fragment {

public FirstActivityFragment(){

}

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

TextView textView = (TextView)v.findViewById(R.id.showFirstFragmentInfo);
final Context context = this.getActivity();
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast hello;
hello = Toast.makeText(context,"hello",Toast.LENGTH_LONG);
hello.show();
}
});
return v;
}

@Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

}

}


为Fragment创建一个xml fragment_first.xml
<?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="match_parent"
android:id="@+id/showFirstFragmentInfo"
android:text="this is a firstFragment"/>
</LinearLayout>
并在一个activity view 中使用
<?xml version="1.0" encoding="utf-8"?>
<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="#33FF00">
<fragment xmlns:android=
"http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fragment"
android:name="com.example.liang.login.FirstActivityFragment"
tools:layout="@layout/fragment_first"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android fragment