Friday 26 September 2014

Set Image Through Button

You can add images in your project through simple copy your image and then past in
res/drawable.



Now your activity_main.xml like this;

<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"
    tools:context=".MainActivity" >


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/img"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Change" />
    </LinearLayout>

</LinearLayout>


Your MainActivity.java like this:

package com.example.imageview;

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

public class MainActivity extends Activity {
Button btn_change;
ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image=(ImageView)findViewById(R.id.img);
        btn_change=(Button)findViewById(R.id.btn);
        btn_change.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
// TODO Auto-generated method stub
image.setImageResource(R.drawable.cloudy);

}
});
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
}

App like this:

  







No comments:

Post a Comment