2011-12-08

在 Android 裡以 ImageView 看照片

練習三件事:挑照片、看照片、顯示路徑。

main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="pickAPhoto"
        android:text="挑照片" />

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <ImageView
            android:id="@+id/iv"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="@string/hello" />

        <TextView
            android:id="@+id/tv"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:gravity="center" />
    </FrameLayout>

</LinearLayout>
PickAPhotoActivity
public class PickAPhotoActivity extends Activity {

    private static final String TAG = "PickAPhotoActivity";
    private static final int REQUEST_CODE = 1;
    private ImageView iv;
    private TextView tv;

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

        this.iv = (ImageView) this.findViewById(R.id.iv);
        this.tv = (TextView) this.findViewById(R.id.tv);
    }

    public void pickAPhoto(View v) {
        Intent it = new Intent(Intent.ACTION_GET_CONTENT);
        it.setType("image/*");
        this.startActivityForResult(it, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != REQUEST_CODE) {
            Log.e(TAG, "不是挑照片");
            return;
        }
        if (resultCode != RESULT_OK) {
            Log.e(TAG, "挑照片失敗");
            return;
        }
        Uri uri = data.getData();
        this.iv.setImageURI(uri);
        this.tv.setText(uri.getPath());
    }
}
相關文章

沒有留言:

張貼留言