对于我的活动,我们的任务是完全以编程方式创建视图(不允许使用XML)。
但是我无法像我在XML文件中所做的那样,获取我的contentEditText和重力来正确设置它们。
这就是我的看法。
public class NoteGridLayout extends GridLayout {
public NoteGridLayout(final Context context, EditText titleEditText, Spinner spinner, EditText contentEditText, Button backButton) {
super(context);
setColumnCount(2);
GridLayout.Spec colSpec, rowSpec;
colSpec = GridLayout.spec(0, 1, 1);
rowSpec = GridLayout.spec(0, 0, 0);
GridLayout.LayoutParams titleParams = new GridLayout.LayoutParams(rowSpec, colSpec);
colSpec = GridLayout.spec(1,1,1);
rowSpec = GridLayout.spec(0,0,0);
GridLayout.LayoutParams spinnerParams = new GridLayout.LayoutParams(rowSpec, colSpec);
colSpec = GridLayout.spec(0,2,1);
rowSpec = GridLayout.spec(1,1,1);
GridLayout.LayoutParams contentParams = new GridLayout.LayoutParams(rowSpec, colSpec);
colSpec = GridLayout.spec(0,2,1);
rowSpec = GridLayout.spec(2,1,0);
GridLayout.LayoutParams buttonParams = new GridLayout.LayoutParams(rowSpec, colSpec);
titleParams.width = 0;
titleParams.height = LayoutParams.WRAP_CONTENT;
spinnerParams.width = 0;
spinnerParams.height = LayoutParams.WRAP_CONTENT;
contentParams.width = 0;
contentParams.height = 0;
buttonParams.width = LayoutParams.MATCH_PARENT;
buttonParams.height = LayoutParams.WRAP_CONTENT;
contentParams.setGravity(Gravity.TOP);
titleEditText.setLayoutParams(titleParams);
spinner.setLayoutParams(spinnerParams);
contentEditText.setLayoutParams(contentParams);
backButton.setLayoutParams(buttonParams);
addView(titleEditText);
addView(spinner);
addView(contentEditText);
addView(backButton);
}
}
我遇到的两个主要问题是: 1. titleEditText似乎没有覆盖整个列,而微调器占据了整个两列。 2.无法设置contentEditText重力,将文本置于框的顶部。
该如何解决这两个问题?
答案 0 :(得分:0)
对于layout_gravity,下面是一个代码段,
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.CENTER;
yourView.setLayoutParams(params);
对于重力,请使用以下行
yourLayout.setGravity(Gravity.CENTER)