Fragment的使用总结和实例详解

本文详细阐述了如何利用Fragment技术实现分屏显示新闻应用。包括左右两个Fragment的布局设计、创建方法、在主Activity中的添加及操作,以及根据不同屏幕尺寸的优化。此外,还介绍了XML布局中`ellipsize`属性的作用,并通过实例展示了如何实现新闻列表的分屏显示。

Fragment

1.碎片的状态和回调
Fragment在其生命周期中的状态一共有运行状态、暂停
状态、停止状态和销毁状态这四种。类似地,每个碎片在其生命周期内也可能会经历这几种
状态,只不过在一些细小的地方会有部分区别。
1. 运行状态
当一个碎片是可见的,并且它所关联的活动正处于运行状态时,该碎片也处于运行
状态。
2. 暂停状态
当一个活动进入暂停状态时(由于另一个未占满屏幕的活动被添加到了栈顶),与
它相关联的可见碎片就会进入到暂停状态。
3. 停止状态
当一个活动进入停止状态时,与它相关联的碎片就会进入到停止状态。或者通过调
用 FragmentTransaction 的 remove()、 replace()方法将碎片从活动中移除,但有在事务提
交之前调用 addToBackStack()方法,这时的碎片也会进入到停止状态。总的来说,进入
停止状态的碎片对用户来说是完全不可见的,有可能会被系统回收。
4. 销毁状态
碎片总是依附于活动而存在的,因此当活动被销毁时,与它相关联的碎片就会进入
到销毁状态。或者通过调用 FragmentTransaction 的 remove()、 replace()方法将碎片从活
动中移除,但在事务提交之前并没有调用 addToBackStack()方法,这时的碎片也会进入
到销毁状态。
2.创建一个分屏的Fragment

1.设计左右两边的布局,左边为Button,右边为一个TextView。那么:
left_fragment.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">

    <!--记:下面Button中layout_gravity和gravity的区别?
        答:layout_gravity:是针对于整个layout当前空间的位置,
        gravity是针对这个Button中文字的位置
    -->
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:text="Button"
        />

</LinearLayout>
right_fragment.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:background="#00FF00"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/textview"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        android:text="This is right fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>
2.通过继承Fragment类,重写onCreateView方法绑定这些xml文件
LeftFragment.java:
package com.example.zhengxie.demo_fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by zheng.xie 
 */

public class LeftFragment extends Fragment {

    //新建一个Fragment时,需要重写onCreateView方法,然后再在
    //activity_main中,将此LeftFragment以name的形式添加
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.left_fragment,container,false);
        return view;
    }
}
RightFragment.java:
package com.example.zhengxie.demo_fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by zheng.xie.
 */

public class RightFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.right_fragment,container,false);
        return view;
    }
}
3.在activity_main.xml中,将这两个Fragment以name的形式加入
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.zhengxie.demo_fragment.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        ></fragment>

    <!--记Fragment在主activity_main中的添加方式-->
    <FrameLayout
        android:id="@+id/right_layout"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent">
    <fragment
        android:id="@+id/right_fragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:name="com.example.zhengxie.demo_fragment.RightFragment"
        android:layout_weight="1"
        ></fragment>

    </FrameLayout>
</LinearLayout>
4.在MainActivity中对fragment进行操作:
MainActivity.java:
package com.example.zhengxie.demo_fragment;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AnotherRightFragment anotherRightFragment = new AnotherRightFragment();
                //getFragmentManager()是Activity中的方法,
                //Return the FragmentManager for interacting with fragments associated
                //with this activity.
                FragmentManager fragmentManager = getFragmentManager();
                //Fragment Transaction将先于activity的状态保存
                //Note: A fragment transaction can only be created/committed prior
                //to an activity saving its state
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();//开始记录一个事物
                //将左边的xml资源替换成右边的Fragment
                // Replace an existing fragment that was added to a container
                fragmentTransaction.replace(R.id.right_layout,anotherRightFragment);
                //在栈中添加这个事物null
                //Add this transaction to the back stack.  This means that the transaction
                //will be remembered after it is committed, and will reverse its operation
                // when later popped off the stack.
                fragmentTransaction.addToBackStack(null);
                //为transaction建立计划,提交事物。
                // Schedules a commit of this transaction.  The commit does
                // not happen immediately; it will be scheduled as work on the main thread
                // to be done the next time that thread is ready.
                fragmentTransaction.commit();
            }
        });
    }
}
3.根据layout和layout-large来区分大小屏

4.笔记记录:xml布局中ellipsize的各个属性作用是什么?
例如对于字符:aaabbbccc 
start's output will be : ...bccc
end's output will be : aaab...
middle's output will be : aa...cc
marquee's output will be : aaabbbccc auto sliding from right to left
5.使用Fragment技术实现的分屏新闻实例的详解(附注释)
1.在MainActivity.java中设置首页显示的页面:分析首页是由一个Fragment嵌套listview来显示的。
package com.example.zhengxie.demo_fragment_wangyinews;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG,"onCreate()");
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
    }
}
2.修改R.layout.activity_main。因为这个xml是要新建一个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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.zhengxie.demo_fragment_wangyinews.MainActivity">

    <fragment
        android:id="@+id/news_title_fragment"
        android:name="com.example.zhengxie.demo_fragment_wangyinews.NewsTitleFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </fragment>
</RelativeLayout>
3.创建完一个fragment之后,需要开始对这个fragment进行onCreateView
package com.example.zhengxie.demo_fragment_wangyinews;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import java.lang.ref.PhantomReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zheng.xie .
 */

public class NewsTitleFragment extends Fragment implements AdapterView.OnItemClickListener{
    private static final String TAG = "NewsTitleFragment";

    private ListView newsTitleListView;
    private List<News> newsList;
    private NewsAdapter adapter;
    private boolean isTwoPane;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.d(TAG,"onAttach");
        //第二步:进行数据和adapter的绑定
        newsList = getNews();
        adapter = new NewsAdapter(activity, R.layout.news_item, newsList);
    }

    @Nullable
    @Override
    /**
     * 这个方法是用来创建listview这个layout布局的。至于这个listview布局中的内容,在上面的onAttach方法中
     * 声明一个adapter
     */
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG,"onCreateView");
        //第一步:声明一个listview
        View view = inflater.inflate(R.layout.news_title_frag,container,false);
        newsTitleListView = (ListView) view.findViewById(R.id.news_title_list_view);
        //第三步:setAdapter
        newsTitleListView.setAdapter(adapter);//通过上面的adapter进行与listview绑定
        newsTitleListView.setOnItemClickListener(this);
        return view;
    }

    /**
     * 第四步:处理用于点击每个item事件的方法
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.d(TAG,"onItemClick");
        News news = newsList.get(position);
        NewsContentActivity.actionStart(getActivity(),news.getTitle(),news.getContent());
    }

    private List<News> getNews() {
        Log.d(TAG,"getNews()");
        List<News> newsList = new ArrayList<News>();
        News news1 = new News();
        news1.setTitle("Succeed in Colleage");
        news1.setContent("College freshman will soon learn");
        newsList.add(news1);
        News news2 = new News();
        news2.setTitle("Google Android ");
        news2.setContent("China!!!!!");
        newsList.add(news2);
        return newsList;
    }
}
4.这个时候,首页的显示完成了。当用户点击了事件按钮的时候,将会实现onItemClick()这个方法
package com.example.zhengxie.demo_fragment_wangyinews;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

/**
 * Created by zheng.xie.
 */

public class NewsContentActivity extends Activity {
    private static final String TAG = "NewsContentActivity";
    public static void actionStart(Context context, String newsTitle, String newsContent) {
        Log.d(TAG,"actionStart");
        //从MainActivity跳转如当前Activity
//Intent传入数据的方法。这里putExtra。取出的时候就使用getIntent().getStringExtra。
//标志位:context, NewsContentActivity.class...
        Intent intent = new Intent(context, NewsContentActivity.class);
        intent.putExtra("news_title", newsTitle);
        intent.putExtra("news_content", newsContent);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG,"onCreate");
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.news_content);
	//这里使用getIntent是因为上面方法中,使用的是将context传入到当前类中
        String newsTitle = getIntent().getStringExtra("news_title");
        String newsContent = getIntent().getStringExtra("news_content");
        //获取一个fragment的实例。使用getFragmentManager().findFragmentById()方法
        NewsContentFragment newsContentFragment = (NewsContentFragment) getFragmentManager().findFragmentById(R.id.news_content_fragment);
        newsContentFragment.refresh(newsTitle, newsContent);
    }
}
5.这个时候加载完毕第二个Intent传入的Activity之后,继续使用fragment的方式,去匹配这个类。
package com.example.zhengxie.demo_fragment_wangyinews;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by zheng.xie.
 */

public class NewsContentFragment extends Fragment {
    private static final String TAG = "NewsContentFragment";

    private View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.news_content_frag, container, false);
        Log.d(TAG,"onCreateView");
        return view;
    }

    public void refresh(String newsTitle, String newsContent) {
        Log.d(TAG,"refresh");
        View visibilityLayout = view.findViewById(R.id.visibiliy_layout);
        visibilityLayout.setVisibility(View.VISIBLE);
        TextView newsTitleText = (TextView) view.findViewById(R.id.news_title);
        TextView newsContentText = (TextView) view.findViewById(R.id.news_content);
        newsTitleText.setText(newsTitle);
        newsContentText.setText(newsContent);
    }
}












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值