在相对布局中添加多个水平视图

时间:2015-12-12 12:55:53

标签: java android android-layout import widget

我需要的是

第1节

水平滚动视图

第2节

水平滚动视图

它可以是动态的没有部分 所以我需要动态地生成它们 但是,如果我使用此代码 只有最后的水平滚动视图WOrks

休息其他不起作用

我的代码;

public class HomeFragment extends Fragment 
    {
      View rootView;
      int i = 0;

    int j =0;
    public HomeFragment(){

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

         rootView = inflater.inflate(R.layout.fragment_home, container, false);
        RelativeLayout rl=(RelativeLayout)rootView.findViewById(R.id.relativelay);
   HorizontalScrollView sv = new HorizontalScrollView(getActivity().getApplicationContext()) ;

       sv =  hsview(100);
        rl.addView(sv);
    sv = hsview(300);
        rl.addView(sv);

              return rootView;

    }


    public HorizontalScrollView hsview(int k)
{



        HorizontalScrollView sv = new HorizontalScrollView(getActivity().getBaseContext());
      sv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        LinearLayout ll = new LinearLayout(getActivity().getApplicationContext());
        LinearLayout.LayoutParams margin = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        margin.setMargins(0,k,0,0);
       ll.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        ll.setOrientation(LinearLayout.HORIZONTAL);

        for (i = k; i < 310; i++) {
            Button b = new Button(getActivity().getApplicationContext());
            b.setText("Button " + i);
          //  b.setLayoutParams(margin);
            ll.addView(b);
        }

        sv.addView(ll);
        return sv;


       }
       }       

1 个答案:

答案 0 :(得分:0)

这可能是因为您使用MATCH_PARENT参数作为Horizo​​ntalScrollView的高度。只需用WRAP_CONTENT替换MATCH_PARENT,如下所示

sv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));