【发布时间】:2018-05-02 11:02:19
【问题描述】:
我的目的是以编程方式在相对布局内创建一个按钮网格。我想以编程方式执行此操作的原因是按钮的数量因情况而异,即我可能需要 12 个按钮而不是 9 个,依此类推。
I managed to do this but with a Linear layout
However, this is the desired outcome
据我所知,我需要在相对布局中创建按钮,但是 this is what happens 当我将布局更改为相对时。它们只是堆叠在一起。
这是创建按钮的代码:
for (int i = 0; i < frows; i++) {
LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.setPadding(0, 40, 0, 0);
for (int j = 0; j < 3; j++) {
ContextThemeWrapper newContext = new ContextThemeWrapper(getBaseContext(), R.style.ExerciseButtonTheme);
eBtn = new Button(newContext);
eBtn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
eBtn.setText("" + (j + 1 + (i * 3)));
eBtn.setId(j + 1 + (i * 3));
eBtn.setBackgroundResource(R.drawable.exercisebutton);
row.addView(eBtn);
eBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), ListActivity.class);
id = "" + view.getId();
intent.putExtra(EXTRA_MESSAGE, id);
startActivity(intent);
}
});
}
layout.addView(row);
}
我花了很多时间试图弄清楚并搜索现有的答案,但无济于事。任何帮助将不胜感激!
编辑
<item android:state_pressed="true">
<shape>
<solid android:color="#449def"/>
<stroke android:width="1dp" android:color="#2f6699"/>
<corners android:radius="6dp"/>
<padding android:left="10dp" android:top="10dp" android:right="10dp"
android:bottom="10dp"/>
</shape>
</item>
<item>
<shape>
<gradient android:startColor="#449def" android:endColor="#2f6699" android:angle="270"/>
<stroke android:width="1dp" android:color="#2f6699"/>
<corners android:radius="4dp"/>
<padding android:left="10dp" android:top="10dp" android:right="10dp"
android:bottom="10dp"/>
</shape>
</item>
【问题讨论】:
标签: java android android-layout