0

我正在试验 Android 片段,因此我创建了两个片段ListFragmentDetailFragment. 问题是,当我单击ListFragment并调用一个DetailFragment方法来显示所选项目时,ListFragment没有结果显示在DetailFragment. 这是DetailFragment代码:

    private static final String DETAIL_FRAG_TAG = "detail_fragment";
private Context appContext = null;
private TextView lblItemDetail = null;
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // inflate the fragment layout
    View rootView = inflater.inflate(R.layout.fragments_detail_fragment, container, false);
    lblItemDetail = (TextView) rootView.findViewById(R.id.lbl_itemDetail);


 //at this point the TextView is not null===>see L0g.i
Log.i(DETAIL_FRAG_TAG, " ---MyDetailFragment---oncreateView()--lblItemDetail =[" +    lblItemDetail + "]");

    // get the fragment activity context
    appContext = this.getActivity();
    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);

}

/**
 * show the details of the item selected on the listFragment.
 * @param itemDetail - the details of the item selected on ListFragment.
 */
public void showLstItemDetail(String itemDetail) {

    if (lblItemDetail != null) {
        // the View to show Text should not be Null.
        lblItemDetail.setText(itemDetail);
    }

    //at this point calling this method shows 
           that    the `TextView` is Null yet it's 
       initialized in the 
        oncreate() as a class member variable ---why am i 
   getting Null after the `oncreate` is finished.
    Log.i(DETAIL_FRAG_TAG,    "------showItemDetail---------msg=[" + itemDetail + "] txt=[" + lblItemDetail + "]");
}



//when I create an instance of `MYDetailFragment`  and call the method to show the details of item Selected on the `DetailFragment` the `TextView` will be null. Why?

   MYDetailFragment detailFrag = new MyDetailFragment();
   detailFrag.showLstItemDetail("Selected List Item");
4

2 回答 2

1

如果有任何有用的信息,请验证以下关于片段的教程点击这里

于 2013-03-01T15:09:35.407 回答
0

在这两行中:

MYDetailFragment detailFrag = new MyDetailFragment();
detailFrag.showLstItemDetail("Selected List Item");

onCreateView()尚未调用。这意味着片段 roo​​tView 从未创建过,并且 TextView 从未创建过!

视图只会在您使用片段事务后创建,将该片段放入布局中,然后片段将附加到活动(onAttach()),并且在更多的回调之后 onCreateView()将被调用。只有这样才能对其进行任何设置。

将参数传递给片段的标准良好做法是使用 Bundle。看一个示例代码:

关于活动:

MYDetailFragment detailFrag = new MYDetailFragment();
Bundle b = new Bundle();
detailFrag.setArguments(b);
b.putString("detail", value);
// then proceed to the fragment transaction

然后在你的片段上:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflate the fragment layout
View rootView = inflater.inflate(R.layout.fragments_detail_fragment, container, false);
lblItemDetail = (TextView) rootView.findViewById(R.id.lbl_itemDetail);
Bundle b = getArguments();
lblItemDetail.setText(b.getString("details"));
于 2013-03-01T15:49:10.197 回答