Add views( buttons, labels, etc ) to a dynamic fragment without using any ressource xml

后端 未结 2 651
谎友^
谎友^ 2021-01-16 04:48

First of all I would like to say, that I want to say \"Hello in here\".

Requirements:

I should make it possible to create a client applicati

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-16 05:25

    I got the same Problem and to my amzement I found a solution! Create a blank XML layout file like this...

    
    
    
    

    In the fragment where your layout is dynamically created, inflate this blank layout XML file.

      @Override
      public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup     container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.blank_layout, container, false);
        return view;
    

    Afterwords, in onViewCreated() method you can create your layout dynamically.

      @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
      super.onViewCreated(view, savedInstanceState);
    
    // This will create the LinearLayout
    LinearLayout ll = new LinearLayout(mContext);
    ll.setOrientation(LinearLayout.VERTICAL);
    
    // Configuring the width and height of the linear layout.
    LinearLayout.LayoutParams llLP = new LinearLayout.LayoutParams(
            //android:layout_width="match_parent" an in xml
            LinearLayout.LayoutParams.MATCH_PARENT,
            //android:layout_height="wrap_content"
            LinearLayout.LayoutParams.MATCH_PARENT);
    ll.setLayoutParams(llLP);
    
    TextView tv = new TextView(mContext);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    
    tv.setLayoutParams(lp);
    //android:text="@string/c4r"
    tv.setText("Hello android !");
    //android:padding="@dimen/padding_medium"
    tv.setPadding(8, 8, 8, 8);
    ll.addView(tv);
    
    ViewGroup viewGroup = (ViewGroup) view;
    viewGroup.addView(ll);
    }
    
    }
    

提交回复
热议问题