2016-01-24 38 views
0

我在创建片段的代码中存在以下问题,这没关系。
我的问题是当我尝试设置他和参数。
这是我的代码。以编程方式创建片段并设置参数

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
     0, ViewGroup.LayoutParams.WRAP_CONTENT); 
params.weight = 1.0f; 

FragmentManager fragmentManager = getFragmentManager(); 
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
FragmentImageList myFragment = new FragmentImageList(); 

fragmentTransaction.add(631, myFragment, "fragmentTag"); 
fragmentTransaction.addToBackStack(null); 
fragmentTransaction.commit(); 

myFragment.getView().setLayoutParams(params); 

然后在控制台中我有以下错误。

Attempt to invoke virtual method 'void android.view.View.setLayoutParams(android.view.ViewGroup$LayoutParams)' on a null object reference 

由于Fragment的视图还没有被创建,其中有意义。 但如何做到这一点来设置创建片段的“参数”。

回答

1

631要传递到:

fragmentTransaction.add(631, myFragment, "fragmentTag"); 

应该是要在其上添加片段的视图id。 请确保631是该视图的ID,否则通过像R.id.yourViewId

+0

因为在此之前,我在代码中创建了LinearLayout,这是他的ID。 目标是创建一个没有GridLayout的行和列的网格。 – OneByte

-1

我不知道你的要求是什么,但我认为你应该充气视图而不是片段。

片段就像占位符,它们会自动填充它们的容器视图(例如FrameLyout),并且您不需要手动分配它们的宽度和高度。但如果你仍然想这样做,你应该在你的片段类中创建视图

@Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
      rootView = inflater.inflate(R.layout.home_fragment, container, false); 

// assign new layout params on rootView here 

---------------------- - - - - - - - - - - 要么 - - - - - - - - - - - - - - - -------------------------------------

使用布局充气器做同样的工作

 //Use Layout inflater 
     LayoutInflater inflater = (LayoutInflater) context 
         .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     //Load layout xml of child layout you want to add 
     View childView= inflater.inflate(R.layout.viewpager_place_holder, null); 


     //Get and Assign values on views of child view 
     ((TextView) childView.findViewById(R.id.pager_title)) 
          .setText("Test"); 

     // Set width and margin on child layout 
     LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
         LinearLayout.LayoutParams.MATCH_PARENT, 
         LinearLayout.LayoutParams.WRAP_CONTENT); 

     layoutParams.setMargins(
          UtilFunctions.getUtilFunctions().dpToPixels(5, 
            context.getResources()), 
          UtilFunctions.getUtilFunctions().dpToPixels(5, 
            context.getResources()), 
          UtilFunctions.getUtilFunctions().dpToPixels(5, 
            context.getResources()), 
          UtilFunctions.getUtilFunctions().dpToPixels(5, 
            context.getResources())); 

     //Add child to the root layout 
     rootLayout.addView(childView, layoutParams); 
+0

为什么要投票? –

+0

感谢您的回复请勿使用它,但它给了我一个想法:) 感谢您的帮助。 – OneByte

0

感谢您的回答,我感到很蠢。
我的目标是用Fragment创建一个网格。
但是这个带参数的整个方案完全没有必要。

@Hitesh Sahu,再次感谢你。
答案的一部分是关键。

片段就像是他们的占位符自动填写其持有 容器视图(如FrameLyout),你不需要手动分配他们的 宽度和高度。


根本就创建在该片段中使用它的另一个RES /布局文件。
只适用于此格:)

相关问题