我试图生成一个网格式的按钮列表。它有效,除了其中一个按钮,它是唯一一个没有drawable
的按钮。我不确定如何使其与其他按钮对齐。
以下是类方法:
// test values
private static final int CURRENT_LEVEL = 8;
private static final int LEVEL_CAP = 20;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.level_select);
generateList();
}
public void generateList() {
GridLayout layout = (GridLayout)findViewById(R.id.mainLayout);
layout.setColumnCount(5);
for (int i = 1; i <= LEVEL_CAP; i++) { // for every level there is
Button btn = new Button(this);
// 200x200 size
btn.setLayoutParams(new LinearLayout.LayoutParams(200, 200));
btn.setTextSize(14);
if (i < CURRENT_LEVEL) { // already completed the level
setTopDrawable(btn, R.drawable.ic_checkmark_holo_light, i);
} else if (i == CURRENT_LEVEL) { // current level being completed
//setTopDrawable(btn, 0, i); // gets the same result as the line below
btn.setText(String.valueOf(i));
} else if (i > CURRENT_LEVEL) { // these are the locked levels
setTopDrawable(btn, R.drawable.ic_lock_lock, i);
}
layout.addView(btn);
}
}
public Button setTopDrawable(Button btn, int id, int i) {
// put the drawable with its id = id on top
btn.setCompoundDrawablesWithIntrinsicBounds(0, id, 0, 0);
btn.setCompoundDrawablePadding(0);
btn.setPadding(0, 20, 0, 20);
btn.setText(String.valueOf(i)); // put the level text under the drawable
return btn;
}
以下是相关布局:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.mikeyaworski.whoisthatyoutuber.LevelSelect" >
<GridLayout
android:id="@+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</GridLayout>
</ScrollView>
这是输出:
如何让按钮8与其他按钮对齐?