로 컬 로 네트워크 그림 읽 기
사고의 방향
구체 적 인 사고방식 은 비교적 간단 하지만 사상 은 매우 단순 하 다.인터넷 주 소 를 입력 하고 단 추 를 누 르 면 네트워크 에서 가 져 온 그림 을 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" >
<EditText
android:id="@+id/et_website"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="please type the url "
/>
<Button
android:id="@+id/btn_get"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
/>
<ImageView
android:id="@+id/iv_picture"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
/>
</LinearLayout>
그리고 메 인 인터페이스의 논리 코드.
package com.example.getphotobyxml;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.service.ImageService;
public class MainActivity extends Activity {
private EditText mEt_url;
private ImageView mIv_picture;
private Button mBtn_get;
/**
* ID
*/
public void init() {
mEt_url = (EditText) findViewById(R.id.et_website);
mIv_picture = (ImageView) findViewById(R.id.iv_picture);
mBtn_get = (Button) findViewById(R.id.btn_get);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
init();
mBtn_get.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String website = mEt_url.getText().toString();
if (website == null || website.equals("")) {
Toast.makeText(MainActivity.this, " !",
Toast.LENGTH_LONG).show();
return;
}
byte[] bytes;
try {
bytes = ImageService.getImage(website);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
bytes.length);
mIv_picture.setImageBitmap(bitmap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/**
* XML , ImageView
* onClickListener,
* @param view
*/
public void getPicture(View view) {
String website = mEt_url.getText().toString();
if (website == null || website.equals("")) {
Toast.makeText(this, " !", Toast.LENGTH_LONG).show();
return;
}
byte[] bytes;
try {
bytes = ImageService.getImage(website);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
bytes.length);
mIv_picture.setImageBitmap(bitmap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
서비스 및 tools 조수
package com.example.service;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.example.utils.StreamTool;
/**
*
*/
public class ImageService {
public static byte[] getImage(String website) throws Exception {
URL url = new URL(website);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200){
InputStream inputStream = conn.getInputStream();
byte[] bytes = StreamTool.read(inputStream);
return bytes;
}
return " ".getBytes();
}
}
package com.example.utils;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
/**
* utils
*/
public class StreamTool {
public static byte[] read(InputStream inputStream) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len = inputStream.read(buf))!=-1){
baos.write(buf, 0 ,len);
}
baos.close();
return buf;
}
}
총결산이 안의 코드 는 매우 간단 하 다.내 가 여기에 코드 를 붙 인 주요 목적 은 층 을 나 누 는 사상 과 재 구성 하 는 예술 을 보 여 주 는 것 이다.
코드 에서 우 리 는 전문 적 인 업 무 를 완성 하기 위해 전문 적 인 종 류 를 만 드 는 것 을 보 았 다.그리고 서로 다른 차원 의 유형,처리 하 는 업무 도 다르다.이렇게 하면 우리 가 대상 을 대상 으로 하 는 방식 으로 프로 그래 밍 하여 더욱 뚜렷 한 논 리 를 가 져 오 는 데 도움 이 된다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin의 기초 - 2부지난 글에서는 Kotlin이 무엇인지, Kotlin의 특징, Kotlin에서 변수 및 데이터 유형을 선언하는 방법과 같은 Kotlin의 기본 개념에 대해 배웠습니다. 유형 변환은 데이터 변수의 한 유형을 다른 데이터...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.