天天看點

Android常用控件之 - ImageViewAndroid常用控件之 - ImageView

轉載請注明出處amoscxy的部落格:https://mp.csdn.net/mdeditor/80144381
  • Android常用控件之 - ImageView

Android常用控件之 - ImageView

ImageView是用來在界面中展示圖檔的控件,圖檔通常放在”drawable”開頭的目錄下,項目建立時通常會有個空的drawable目錄,不過這個目錄沒有指定具體的分辨率,一般不适用它來放置圖檔,這裡我們在res目錄下建立一個drawable-xhdpi目錄,在這個目錄中存放圖檔

  • 項目結構:
    Android常用控件之 - ImageViewAndroid常用控件之 - ImageView
  • 最終效果:
    Android常用控件之 - ImageViewAndroid常用控件之 - ImageView
  • MainActivity.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="24sp"
        android:textColor="#00ff00"
        android:text="This is TextView" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button"
        android:textAllCaps="false" />
    <ImageView
        android:id="@+id/image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/img_1"
        />
</LinearLayout>
           

可以看到,這裡使用

android:src

屬性給ImageView指定了一張圖檔

  • MainActivity :
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editText;

    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        imageView  = (ImageView) findViewById(R.id.image_view);
        findViewById(R.id.progress_bar);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:                imageView.setImageResource(R.drawable.img_2);
                break;
            default:
                break;
        }
    }
}
           

還可以動态更改ImageView顯示的圖檔,點選按鈕時,調用ImageView的setImageResource()方法将顯示的圖檔改成img_2

  • 顯示效果
    Android常用控件之 - ImageViewAndroid常用控件之 - ImageView
轉載請注明出處amoscxy的部落格:https://mp.csdn.net/mdeditor/80144381