将onClick添加到以编程方式创建的按钮

时间:2015-11-27 19:37:00

标签: android

TextViewButton以编程方式创建并添加到预先存在的垂直布局中,使其看起来像一个垂直的视图列表。这些视图仅基于用户将数据输入edittext而创建,并且该数据会保存到ArrayList

如何在我的垃圾箱中添加onClick功能?以编程方式创建的按钮,允许他们删除与之关联的视图。

public static ArrayList<String> deckNameArray = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    LinearLayout mainLayout = (LinearLayout)findViewById(R.id.mainLayout);

    for(int i = 0; i < deckNameArray.size(); i++)
    {
        LinearLayout layout = new LinearLayout(this);
        if ((i % 2) == 0) {
            layout.setBackgroundColor(Color.CYAN);
        } else {
            layout.setBackgroundColor(Color.WHITE);
        }
        layout.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layout.setLayoutParams(layoutParams);
        layout.setPadding(10, 5, 10, 5);
        layout.setWeightSum(5);
        mainLayout.addView(layout);

        LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 4f);
        TextView deckName = new TextView(this);
        deckName.setText(deckNameArray.get(i));
        deckName.setTextColor(Color.BLACK);
        deckName.setTextSize(18);
        deckName.setGravity(Gravity.CENTER_VERTICAL);
        deckName.setLayoutParams(textViewParams);
        layout.addView(deckName);

        LinearLayout.LayoutParams imageButtonParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
        ImageButton remove = new ImageButton(this);
        remove.setImageResource(R.mipmap.trash);
        if ((i % 2) == 0) {
            remove.setBackgroundColor(Color.CYAN);
        } else {
            remove.setBackgroundColor(Color.WHITE);
        }
        remove.setLayoutParams(imageButtonParams);
        layout.addView(remove);
    }

2 个答案:

答案 0 :(得分:8)

答案 1 :(得分:4)

您可以使用与以下示例类似的代码在任何视图上设置点击侦听器:

<dependency>
  <groupId>org.nfctools</groupId>
  <artifactId>nfctools-examples</artifactId
  <version>1.0</version>
</dependency>