how to create a new imageview in android java

how to create a new imageview in android java

To create a new ImageView in Android using Java, you can use the ImageView class and the setImageResource method.

Here is an example of how you can create an ImageView and set an image to it in an Android activity:

refe‮ot r‬:lautturi.com
import android.widget.ImageView;

public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Create a new ImageView
    ImageView imageView = new ImageView(this);

    // Set an image to the ImageView
    imageView.setImageResource(R.drawable.image);

    // Add the ImageView to the layout
    LinearLayout layout = findViewById(R.id.layout);
    layout.addView(imageView);
  }
}

This code creates a new ImageView object called imageView and sets an image to it using the setImageResource method. The image is specified using the R.drawable.image resource identifier, which refers to an image file in the res/drawable directory of the project.

The ImageView is then added to a layout using the addView method of the LinearLayout class. The layout is specified using the R.id.layout resource identifier, which refers to a layout element in the XML layout file activity_main.xml.

You can also use the android.support.v7.widget.AppCompatImageView class to create an ImageView if you are using the Android Support Library.

import android.support.v7.widget.AppCompatImageView;

public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Create a new ImageView
    AppCompatImageView imageView = new AppCompatImageView(this);

    // Set an image to the ImageView
    imageView.setImageResource(R.drawable.image);

    // Add the ImageView to the layout
    LinearLayout layout = findViewById(R.id.layout);
    layout.addView(imageView);
  }
}

This code is similar to the previous example, but it uses the AppCompatImageView class instead of the ImageView class. The AppCompatImageView class is

Created Time:2017-11-01 12:05:16  Author:lautturi