使用自定义适配器设置按钮ID

时间:2016-06-28 10:47:40

标签: android android-layout

这将是创建每行有四个或更多按钮的垂直直线布局的更好方法

我遇到的问题如下:

  • 手动设置每个按钮的ID将导致大量重复代码,更多资源使用,您必须更改每个人以添加功能或更改某些内容(我认为使用适配器将是最有效的方式,但...)
  • 据我所知,使用CustomAdapter无法帮助您为按钮设置唯一ID

您是否可以使用适配器为每行按钮设置不同的ID?

示例:

second button of third row: r3b2
fifth button of first row: r1b5

感谢。

1 个答案:

答案 0 :(得分:0)

您可以在我们的Activity类中以编程方式创建按钮,如下所示

LinearLayout layout = (LinearLayout) view.findViewById(R.id.layout); // the layout in which u want to display the buttons
    layout.setOrientation(LinearLayout.VERTICAL);

    int count = 1;
    for (int i = 0; i < 5; i++) { // i = row count
        LinearLayout row = new LinearLayout(getActivity());
        row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        for (int j = 0; j < 7; j++) { // j = column count (create 7 buttons in each row)
                int id = count;
                final Button btnTag = new Button(getActivity());
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT);
                params.weight = 1;
                params.gravity = Gravity.CENTER;
                btnTag.setLayoutParams(params);
                btnTag.setBackgroundColor(Color.parseColor("#ffffff"));
                String dateSuffix = count + getDayNumberSuffix(count);
                btnTag.setTag(dateSuffix);
                btnTag.setId(id);
                btnTag.setText(count + "");
                btnTag.setTextSize(12.0f);
                    btnTag.setOnClickListener(getOnClickDoSomething(btnTag, count));
                row.addView(btnTag);
                count++;
        }
        layout.addView(row);
    }

View.OnClickListener getOnClickDoSomething(final Button btnTag, final int count) {
    return new View.OnClickListener() {
        public void onClick(View v) {
            // here you can do what u want to do on button click
        }
}