Remove View dynamically using Java code

Last post "Insert ImageView dynamically using Java code", by clicking on buttons. Removing function is added here to remove clicked ImageView from parent ViewGroup.

Remove View dynamically using Java code


Modify the Java code from last post, adding OnClickListener to the ImageViews to remove itself from its parent.
package com.example.androidinsertimages;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

Button addinHorizontalScrollView, addinScrollView;
LinearLayout inHorizontalScrollView, inScrollView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

inHorizontalScrollView = (LinearLayout)findViewById(R.id.inhorizontalscrollview);
inScrollView = (LinearLayout)findViewById(R.id.inscrollview);

addinHorizontalScrollView = (Button)findViewById(R.id.addinhorizontalscrollview);
addinHorizontalScrollView.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
addImageView(inHorizontalScrollView);
}});

addinScrollView = (Button)findViewById(R.id.addinscrollview);
addinScrollView.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
addImageView(inScrollView);
}});

}

private void addImageView(LinearLayout layout){
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_launcher);
layout.addView(imageView);

imageView.setOnClickListener(viewOnClickListener);
}

OnClickListener viewOnClickListener
= new OnClickListener(){

@Override
public void onClick(View v) {
ViewGroup parent = (ViewGroup)v.getParent();
parent.removeView(v);
}
};
}



The layout file refer to last post.


0 Response to "Remove View dynamically using Java code"

Posting Komentar