如何添加两个按钮来滚动片段

时间:2013-05-16 12:53:32

标签: java android

我有DetailsFragment类,这个类将两个按钮添加到“fragment”xml,但是当我向“scroller”添加两个按钮时,程序显示expiation“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>

2 个答案:

答案 0 :(得分:0)

错误说明:

ScrollView can host only one direct child

所以你应该做的是在LinearLayout内创建一个布局(RelativeLayout / ScrollView),并将你的按钮放在这个布局中。像这样:

 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);

答案 1 :(得分:0)

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

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);