A TextView
and Button
are programmatically created and added to a pre-existing vertical layout making it look like a vertical list of views. These views are only created based off the user entering data into an edittext
and that data being saved into an ArrayList
.
How can I add an onClick
function to my 'trash' buttons that are programmatically created that would allow them to remove the view they are associated with.
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);
}
remove.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
See http://developer.android.com/reference/android/widget/Button.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With