如何为已经拥有父项的指定子项调用子项的父项

时间:2013-08-22 20:10:18

标签: android

这是代码:

public class HelpDetailsFragment extends Fragment
{
private static final String TAG = "MeMoGame";
public static HelpDetailsFragment newInstance(int index) 
{
    HelpDetailsFragment detailFragment = new HelpDetailsFragment();
    Bundle bundleArgs = new Bundle();
    bundleArgs.putInt("index", index);
    detailFragment.setArguments(bundleArgs);
    return detailFragment;
}   // newInstance()

@Override
public View onCreateView(LayoutInflater inflater,
             ViewGroup container,
             Bundle savedInstanceState)
{
    if(container == null)
    {
    Log.i(TAG, "Different layouts and in one this fragment's containing frame does not exist.");

        return null;
    } else {
        // I checked that container is NOT null
        Log.i(TAG, "This is the parent view that the fragment's UI should be attached to.");
    }
    View mView = new View(getActivity());
    container.addView(mView);
    return container;
}

出现此错误消息: AndroidRuntime(785):引起:java.lang.IllegalStateException:指定的子节点已经有父节点。您必须首先在孩子的父母身上调用removeView()。

有人可以解释我做错了吗?

当我这样做时:

View mView = new View(getActivity());
TextView text = (TextView) new TextView()
mView.addView(text);
return mView;

我收到相同的错误消息。

我的救恩在于:

    @Override
public View onCreateView(LayoutInflater inflater,
         ViewGroup container,
         Bundle savedInstanceState)
{
    Context context = getActivity();

    FrameLayout frameLayout = new FrameLayout(context);
        int height = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 50, getActivity()
                .getResources().getDisplayMetrics());
        int padding = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 10, context
                .getResources().getDisplayMetrics());

        // set the header
        TextView headText = new TextView(context);
        headText.setHeight(height);
        headText.setPadding(padding, 0, 0, 0);
        headText.setTextAppearance(context, R.style.details_Header);
        headText.setText(HelpScreenData.HELP_HEADERS[getCurrentIndex()]);   
        frameLayout.addView(headText);

        ScrollView scroller = new ScrollView(context);
            // set detail text
            TextView detailText = new TextView(context);    
            detailText.setPadding(padding, padding + height, padding, padding);
            detailText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
             detailText.setText(HelpScreenData.HELP_DETAILS[getCurrentIndex()]);        
        scroller.addView(detailText);
    frameLayout.addView(scroller);

    return frameLayout;

}   // onCreateView()

仍然非常欢迎解释!

1 个答案:

答案 0 :(得分:2)

这里的问题是你要返回容器 - return container;你应该在你的情况下返回mView,容器是活动布局中片段的实际容器