2

嗨,我正在尝试将一个按钮加载到视图寻呼机中,并且我已将其加载,但它目前正在填充整个屏幕,我希望它将内容包装到其确切大小,然后将其放置在屏幕中间。我试图为按钮设置布局参数,但是当我运行应用程序时它仍然填充父级。有谁知道如何以编程方式设置按钮的布局和位置?

这是我到目前为止所尝试的

@Override
        public Object instantiateItem(View collection, int position) {

            RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            rel_btn.addRule(RelativeLayout.CENTER_VERTICAL);
            rel_btn.addRule(RelativeLayout.CENTER_HORIZONTAL);
            rel_btn.height = 60;
            rel_btn.width = 60;
            Button tv = new Button(cxt);
            tv.setLayoutParams(rel_btn);
            tv.setText("League " + (position+1));
            tv.setTextColor(Color.WHITE);
            tv.setTextSize(30);
            tv.setBackgroundDrawable(getResources().getDrawable(R.drawable.ls_level_eng1));

            ((ViewPager) collection).addView(tv,0);

            return tv;
        }
4

1 回答 1

1

您通过代码执行此操作有什么特别的原因吗?您可以简单地扩充布局并使用布局编辑器来帮助您调整Button. 这样你就不会猜太多了。

public Object instantiateItem(View collection, int position) {

final LayoutInflater mLayoutInflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

final View view = inflater.inflate(R.layout.your_layout, null);

((ViewPager) collection).addView(view, 0);

return view;

在这种情况下,您需要这样做。我在代码中添加了注释。

    public Object instantiateItem(View collection, int position) {

    // Create your LayoutParams
    final RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);

    // Add your rules
    rel_btn.addRule(RelativeLayout.CENTER_VERTICAL);
    rel_btn.addRule(RelativeLayout.CENTER_HORIZONTAL);

    // And anything extra
    rel_btn.height = 60;
    rel_btn.width = 60;

    // Create a new RelativeLayout for your RelativeLayout.LayoutParams
    RelativeLayout relativeLayout = new RelativeLayout(MainActivity.this);

    // Give your RelativeLayout LayoutParams
    relativeLayout.setLayoutParams(rel_btn);

    // Create your Button
    Button tv = new Button(MainActivity.this);
    tv.setText("League " + (position + 1));
    tv.setTextColor(Color.WHITE);
    tv.setTextSize(30);
    tv.setLayoutParams(rel_btn);
    // You don't need to use setBackgroundDrawable if you're only
    // grabbing a Resource
    tv.setBackgroundResource(R.drawable.ls_level_eng1);

    // Add your Button to your RelativeLayout
    relativeLayout.addView(tv);

    // Return your RelativeLayout
    ((ViewPager)collection).addView(relativeLayout, 0);
    return relativeLayout;
}
于 2012-07-14T14:42:03.393 回答