gpt4 book ai didi

Android以编程方式设置按钮布局

转载 作者:行者123 更新时间:2023-11-29 02:03:10 25 4
gpt4 key购买 nike

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

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

@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;
}

最佳答案

您通过代码执行此操作有什么特别的原因吗?您可以简单地扩充布局并使用布局编辑器来帮助您调整您的 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;
}

关于Android以编程方式设置按钮布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11484579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com