0

我有 DetailsFragment 类,这个类向“fragment”xml 添加两个按钮,但是当我向“scroller”添加两个按钮时,程序显示“ScrollView 只能承载一个直接子项”。请帮我在java代码中添加两个按钮到“scroller”。

public class DetailsFragment extends Fragment {

      @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            if (container == null) {
                return null;
            }
     LinearLayout linearLayout = (LinearLayout)findViewById(R.id.t);
            ScrollView scroller = new ScrollView(getActivity());
            Button m =new  Button(getActivity());
            m.setText("adfgadgfdsfg");
            m.setWidth(100);
            m.setHeight(30);
            m.setTextSize(30);
           scroller.addView(m);

     //*** expiation in this code but when i clear m1 code is work   
            Button m1 =new  Button(getActivity());
            m1.setText("adfgadgfdsfg");
            m1.setWidth(100);
            m1.setHeight(30);
            m1.setTextSize(30);
           scroller.addView(m1);


        }
    }

代码xml布局

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ti"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <fragment 
            android:id="@+id/titles"
            android:layout_width="match_parent" 
            android:layout_height="match_parent"
           android:background="@color/color_detial_fragment" 

             />
           <LinearLayout 
           android:id="@+id/t"
        android:layout_width="match_parent" 
        android:layout_height="match_parent"
          ></LinearLayout>
</FrameLayout>
4

2 回答 2

0

正如你的错误状态:

ScrollView can host only one direct child

所以你应该做的是在里面创建一个布局(LinearLayout/ RelativeLayoutScrollView,然后把你的按钮放在这个布局里面。像这样:

 LinearLayout ll = (LinearLayout)findViewById(R.id.yourLinearLayout);
 Button m =new  Button(getActivity());
 m.setText("adfgadgfdsfg");
 m.setWidth(100);
 m.setHeight(30);
 m.setTextSize(30);
 ll.addView(m); 

 Button m1 =new  Button(getActivity());
 m1.setText("adfgadgfdsfg");
 m1.setWidth(100);
 m1.setHeight(30);
 m1.setTextSize(30);
 ll.addView(m1);

 scroller.addView(ll);
于 2013-05-16T12:55:58.017 回答
0

我们不能向滚动视图添加两个孩子,它只允许一个孩子。创建一个线性布局并向该布局添加按钮,然后将此布局添加到滚动视图。

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.layout1);
Button btn = new Button(this); 
btn.setText("MyButton"); 
linearLayout.addView(btn); 

Button btn2 = new Button(this); 
btn2.setText("MyButton"); 
linearLayout.addView(btn2); 

scrollview.addView(linearLayout);
于 2013-05-16T12:56:09.327 回答