Android-20170412

来源:互联网 发布:淘宝店招图片怎么做 编辑:程序博客网 时间:2024/06/06 03:13

Building a Dynamic UI with fragments

1.fragment的创建

  新建一个类继承Fragment类,完善它的onCreateView方法。

import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.ViewGroup;public class ArticleFragment extends Fragment {    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,        Bundle savedInstanceState) {        // Inflate the layout for this fragment        return inflater.inflate(R.layout.article_view, container, false);    }}
2.用xml布局文件将fragment加入到Activity中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="horizontal"    android:layout_width="fill_parent"    android:layout_height="fill_parent">    <fragment android:name="com.example.android.fragments.HeadlinesFragment"              android:id="@+id/headlines_fragment"              android:layout_weight="1"              android:layout_width="0dp"              android:layout_height="match_parent" />    <fragment android:name="com.example.android.fragments.ArticleFragment"              android:id="@+id/article_fragment"              android:layout_weight="2"              android:layout_width="0dp"              android:layout_height="match_parent" /></LinearLayout>
自己写的时候测试,id一定要写

3.为Activity添加fragment

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/fragment_container"    android:layout_width="match_parent"    android:layout_height="match_parent" />
import android.os.Bundle;import android.support.v4.app.FragmentActivity;public class MainActivity extends FragmentActivity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.news_articles);        // Check that the activity is using the layout version with        // the fragment_container FrameLayout        if (findViewById(R.id.fragment_container) != null) {            // However, if we're being restored from a previous state,            // then we don't need to do anything and should return or else            // we could end up with overlapping fragments.            if (savedInstanceState != null) {                return;            }            // Create a new Fragment to be placed in the activity layout            HeadlinesFragment firstFragment = new HeadlinesFragment();            // In case this activity was started with special instructions from an            // Intent, pass the Intent's extras to the fragment as arguments            firstFragment.setArguments(getIntent().getExtras());            // Add the fragment to the 'fragment_container' FrameLayout            getSupportFragmentManager().beginTransaction()                    .add(R.id.fragment_container, firstFragment).commit();        }    }}
官网上用的是v4的包,有点老了,现在用app的包。也不必特意去继承FragmentActivity。

替换Fragment就是将add方法改为replace。

请谨记,当您执行替换或移除片段等片段事务时,通常最好让用户能够回退并“撤消”更改。 要让用户回退所执行的片段事务,您必须先调用addToBackStack(),然后再提交 FragmentTransaction

// Create fragment and give it an argument specifying the article it should showArticleFragment newFragment = new ArticleFragment();Bundle args = new Bundle();args.putInt(ArticleFragment.ARG_POSITION, position);newFragment.setArguments(args);FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();// Replace whatever is in the fragment_container view with this fragment,// and add the transaction to the back stack so the user can navigate backtransaction.replace(R.id.fragment_container, newFragment);transaction.addToBackStack(null);// Commit the transactiontransaction.commit();
记住Fragment的操作要使用transaction

4.fragment之间的通信

通信主要依赖搭载这个fragment的activity

activity获取其中fragment的信息:

在fragment实现中定义一个interface,比如叫mCallBack,mCallBack中定义一个用来通信的函数,然后利用在父类中实现这个通信函数来达到获取fragment中信息的目的。

public class HeadlinesFragment extends ListFragment {    OnHeadlineSelectedListener mCallback;    // Container Activity must implement this interface    public interface OnHeadlineSelectedListener {        public void onArticleSelected(int position);    }    @Override    public void onAttach(Activity activity) {        super.onAttach(activity);        // This makes sure that the container activity has implemented        // the callback interface. If not, it throws an exception        try {            mCallback = (OnHeadlineSelectedListener) activity;        } catch (ClassCastException e) {            throw new ClassCastException(activity.toString()                    + " must implement OnHeadlineSelectedListener");        }    }    ...}
    @Override    public void onListItemClick(ListView l, View v, int position, long id) {        // Send the event to the host activity        mCallback.onArticleSelected(position);    }
public static class MainActivity extends Activity        implements HeadlinesFragment.OnHeadlineSelectedListener{    ...    public void onArticleSelected(int position) {        // The user selected the headline of an article from the HeadlinesFragment        // Do something here to display that article    }}
public static class MainActivity extends Activity        implements HeadlinesFragment.OnHeadlineSelectedListener{    ...    public void onArticleSelected(int position) {        // The user selected the headline of an article from the HeadlinesFragment        // Do something here to display that article        ArticleFragment articleFrag = (ArticleFragment)                getSupportFragmentManager().findFragmentById(R.id.article_fragment);        if (articleFrag != null) {            // If article frag is available, we're in two-pane layout...            // Call a method in the ArticleFragment to update its content            articleFrag.updateArticleView(position);        } else {            // Otherwise, we're in the one-pane layout and must swap frags...            // Create fragment and give it an argument for the selected article            ArticleFragment newFragment = new ArticleFragment();            Bundle args = new Bundle();            args.putInt(ArticleFragment.ARG_POSITION, position);            newFragment.setArguments(args);            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();            // Replace whatever is in the fragment_container view with this fragment,            // and add the transaction to the back stack so the user can navigate back            transaction.replace(R.id.fragment_container, newFragment);            transaction.addToBackStack(null);            // Commit the transaction            transaction.commit();        }    }}




0 0
原创粉丝点击