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

th3*_*r0d 5 android

A 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);
    }
Run Code Online (Sandbox Code Playgroud)

Qua*_*ger 8

remove.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
             // Perform action on click
         }
     });
Run Code Online (Sandbox Code Playgroud)

请参阅http://developer.android.com/reference/android/widget/Button.html


fra*_*nch 5

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

View myView;

myView.setOnClickListener(new OnClickListener() {
    @Override public void onClick(View v) {
         // TODO your logic here
    }
}
Run Code Online (Sandbox Code Playgroud)