Insert ImageView dynamically using Java code
Here demonstrate how to create and add ImageView in LinearLayout (inside HorizontalScrollView/ScrollView) dynamically using Java code.package com.example.androidinsertimages;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
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);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />
<Button
android:id="@+id/addinhorizontalscrollview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add in HorizontalScrollView"/>
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/inhorizontalscrollview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
<Button
android:id="@+id/addinscrollview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add in ScrollView"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/inscrollview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</LinearLayout>
We can also remove the ImageViews using Java code, refer to next post, "Remove View dynamically using Java code".
0 komentar:
Posting Komentar