我正在 android Studio 中开发应用程序,现在我遇到了一个奇怪的问题。
我有一个 tableRow
,其中包含 TextView
和 Button
。
我以编程方式构建它们,我希望 tableRow
内的按钮
与屏幕的右侧对齐。
我已经尝试过很多选项,例如:
button.setGravity(Gravity.RIGHT)
和 button.setGravity(Gravity.END)
并尝试在 layout_width
中使用 fill_parent
向表格提供布局参数,但似乎不起作用。
这是我构建 TableRow
的代码部分:
TableRow new_tablerow = new TableRow(getContext());
layout_pickup_passengers.addView(new_tablerow);
LinearLayout.LayoutParams rowParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
new_tablerow.setLayoutParams(rowParams);
//GLOBAL PASSENGERS
TextView text_pass_type = new TextView(getContext());
new_tablerow.addView(text_pass_type);
text_pass_type.setTextColor(getResources().getColor(R.color.black));
text_pass_type.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
text_pass_type.setText("> Passageiros");
//BUTTON
// Button
final Button button_numberPickerDialog = new Button(getContext());
button_numberPickerDialog.setBackgroundResource(R.color.wallet_bright_foreground_holo_dark);
new_tablerow.addView(button_numberPickerDialog);
button_numberPickerDialog.setGravity(Gravity.RIGHT);
这就是我得到的:
所以你只能看到里面的文本向右对齐(0数字),而我希望按钮向右对齐而不是里面的文本。
最佳答案
你在这里提到的方法“setGravity(int)
”并不能像你想象的那样工作,因为该方法的工作原理与xml中的属性“andriod:gravity
”相同,显然不会影响你定义的按钮。
实际上,我想知道为什么你坚持以编程方式构建它们。我想如果你用 xml 构建它们,使用“android :layout_gravity
”就可以了。
我尝试使用RalitiveLayout
来使其工作,代码如下:
//TableRow new_tablerow = new TableRow(getBaseContext());
//layout_pickup_passengers.addView(new_tablerow);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout relativeLayout = new RelativeLayout(this);
layout_pickup_passengers.addView(relativeLayout,params);
//GLOBAL PASSENGERS
TextView text_pass_type = new TextView(getBaseContext());
RelativeLayout.LayoutParams lp_text = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
lp_text.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
text_pass_type.setTextColor(getResources().getColor(R.color.colorPrimary));
text_pass_type.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
text_pass_type.setText("> Passageiros");
relativeLayout.addView(text_pass_type,lp_text);
//BUTTON
// Button
final Button button_numberPickerDialog = new Button(getBaseContext());
button_numberPickerDialog.setBackgroundResource(R.color.colorPrimaryDark);
RelativeLayout.LayoutParams lp_button = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
lp_button.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
relativeLayout.addView(button_numberPickerDialog,lp_button);
也许我对你的代码做了一些更改。 它会牺牲你吗? enter image description here
关于java - Android Studio : Button alignment in table row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43476085/