Android学习笔记(Google官方教程)(四)

用Fragment创建动态UI

创建Fragment

  • 引入v4包或者v7包

创建一个Fragment类

  • 需要重写关键的生命周期方法
  • 与Activity不同的是,Fragment是回调onCreateView()来定义布局

    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);
        }
    }
    

使用XML为Activity添加一个Fragment

public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.news_articles);
    }
}
  • v7包应该继承ActionBarActivity

构建合理的UI界面

  • 使用FragmentManager去创建动态界面
在运行时为Activity添加Fragment
  • 用FragmentManager创建FragmentTransaction
  • 在Activity的onCreate()方法调用时初始化Fragments
  • Activity必须拥有View组件插入Fragment

    getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
    
用一个Fragment替换另一个
  • 为了让用户取消fragment的转换,在提交事务之前必须调用 addToBackStack()

    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();
    
  • addToBackStack()带一个指定的String参数,默认传递null

和其他Fragments进行通信

定义接口

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");
    }
}

...
}

* Fragment可以调用onArticleSelected()方法来传递给Activity信息,activity需要实现接口

传递给Fragment信息

  • 通过findViewById()直接调用Fragment的公有方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值