Android 学习(三)上: UI 控件

UI
·textview1:
public int getResourceId(String name) {
    try {
        // 根据资源的ID的变量名获得Field的对象,使用反射机制来实现的
        Field field = R.drawable.class.getField(name);
        // 取得并返回资源的id的字段(静态变量)的值,使用反射机制
        return Integer.parseInt(field.get(null).toString());
    } catch (Exception e) {
        // TODO: handle exception
    }
    return 0;
}
String html = "图像1<img src='image1'/>图像2<img src='image2'/>图像3<img src='image3'/><p>";
html += "图像4<a href='http://www.baidu.com'><img src='image4'></a>图像5<img src='image5'/>";
CharSequence charSequence = Html.fromHtml(html, new ImageGetter() {
 
    @Override
    public Drawable getDrawable(String source) {
        // TODO Auto-generated method stub
        // 获得系统资源的信息,比如图片信息
        Drawable drawable = getResources().getDrawable(
                getResourceId(source));
        // 第三个图片文件按照50%的比例进行压缩
        if (source.equals("image3")) {
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth() / 2,
                    drawable.getIntrinsicHeight() / 2);
        } else {
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
        }
        return drawable;
    }
}, null);
textView.setText(charSequence);
//Sets the movement method (arrow key handler) to be used for this TextView. This can be null to disallow using the arrow keys to move the cursor or scroll the view. 
textView.setMovementMethod(LinkMovementMethod.getInstance());
·textView2:
·注意需要创建Activity1.java
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView textView = (TextView) this.findViewById(R.id.textview);
    String text1 = "显示Activity1";
    // 主要是用来拆分字符串
    SpannableString spannableString = new SpannableString(text1);
    spannableString.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(Main.this, Activity1.class);
            startActivity(intent);
        }
    }, 0, text1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(spannableString);
    textView.setMovementMethod(LinkMovementMethod.getInstance());
}
·textView3:
跑马灯效果
// Boolean that controls whether a view can take focus while in touch mode. 
android:focusableInTouchMode="true"
// If set, causes words that are longer than the view is wide to be ellipsized instead of broken in the middle. 
android:ellipsize="marquee"
// The number of times to repeat the marquee animation. 
android:marqueeRepeatLimit="marquee_forever"
String html = "美国科学家罗伯特J。<a href='http://www.baidu.com'>勒夫科维兹</a>(Robert J. Lefkowitz)";
CharSequence charSequence = Html.fromHtml(html);
textView1.setText(charSequence);
textView1.setMovementMethod(LinkMovementMethod.getInstance());
·EditText1:
·实现表情输入
try {
    Field field = R.drawable.class.getDeclaredField("face"
            + randomId);
    int resourceId = Integer.parseInt(field.get(null)
            .toString());
    // 在android中要显示图片信息,必须使用Bitmap位图的对象来装载
    Bitmap bitmap = BitmapFactory.decodeResource(
            getResources(), resourceId);
    ImageSpan imageSpan = new ImageSpan(Main.this, bitmap);
    SpannableString spannableString = new SpannableString(
            "face");
    spannableString.setSpan(imageSpan, 0, 4,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    editText.append(spannableString);
} catch (Exception e) {
    // TODO: handle exception
}
·EditText2:
·输入特定字符:
//If set, specifies that this TextView has a numeric input method and that these specific characters are the ones that it will accept. 
android:digits="0123456789"
android:digits="qwertyuiopasdfghjklzxcvbnm"
//The type of data being placed in a text field, used to help an input method decide how to let the user enter text. 
android:inputType="number|textCapCharacters"
·AutoCompleteTextView/MultiAutoCompleteTextView:
auto = (AutoCompleteTextView) this.findViewById(R.id.autotext);
String[] autoStrings = new String[] { "联合国", "联合国安理会", "联合国五个常任理事国",
        "Google", "Google Map" };
// 第二个参数表示适配器的下拉风格
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main.this,
        android.R.layout.simple_dropdown_item_1line, autoStrings);
auto.setAdapter(adapter);
 
mul = (MultiAutoCompleteTextView) this.findViewById(R.id.mul);
mul.setAdapter(adapter);
mul.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());// 完成对选项的拆分的功能,以逗号进行拆分
·RadioButton:
·单选按钮的使用:
int len = group.getChildCount();// 获得单选按钮组的选项个数
String msgString = "";
for (int i = 0; i < len; i++) {
    RadioButton radioButton = (RadioButton) group.getChildAt(i);
    if (radioButton.isChecked()) {
        msgString = radioButton.getText().toString();
        break;
    }
}
Toast.makeText(Main.this, msgString, 1).show();
·ToggleButton:
开关按钮:实现布局内横向和纵向的排列
ToggleButton toggle=(ToggleButton)findViewById(R.id.toggleButton1);
final LinearLayout layout=(LinearLayout)findViewById(R.id.lLayout);
toggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
        if(arg1){
            //设置垂直布局
            layout.setOrientation(1);
        }else{
            //设置水平布局
            layout.setOrientation(0);
        }
    }
});
·CheckBox:略
·
·SeekBar 拖动条
需要实现接口:
OnSeekBarChangeListener
Layout中
android:max="100"
android:progress="30" 
android:secondaryProgress="60"//第二位置进度
·在OnCreate事件中加入:
seekBar1.setOnSeekBarChangeListener(this);
seekBar2.setOnSeekBarChangeListener(this);
实现如下方法:
// 当滑动滑竿的时候会触发的事件
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
        boolean fromUser) {
    // TODO Auto-generated method stub
    if (seekBar.getId() == R.id.seekbar1) {
        textView1.setText("seekbar1的当前位置是:" + progress);
    } else {
        textView2.setText("seekbar2的当前位置是:" + progress);
    }
}
// 表示从哪里开始拖动
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    if (seekBar.getId() == R.id.seekbar1) {
        textView1.setText("seekbar1开始拖动");
    } else {
        textView1.setText("seekbar2开始拖动");
    }
}
// 表示从哪里结束拖动
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    if (seekBar.getId() == R.id.seekbar1) {
        textView1.setText("seekbar1停止拖动");
    } else {
        textView1.setText("seekbar2停止拖动");
    }
}
·ImageView1:
//Controls how the image should be resized or moved to match the size of this ImageView. 
android:scaleType="center"
//Sets a drawable as the content of this ImageView. 
android:src="@drawable/background"
// 设置第一个图片的比例大小
// 表示宽度:200高度是100
imageView.setLayoutParams(new LinearLayout.LayoutParams(200, 100));
·ImageView2:实现图片的裁剪和显示功能:
package com.android.myimageview;
import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class Main extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    private Button selectImageBtn;
    private Button cutImageBtn;
    private ImageView imageView;
    // 声明两个静态的整型变量,主要是用于意图的返回的标志
    private static final int IMAGE_SELECT = 1;// 选择图片
    private static final int IMAGE_CUT = 2;// 裁剪图片
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        selectImageBtn = (Button) this.findViewById(R.id.selectImageBtn);
        cutImageBtn = (Button) this.findViewById(R.id.cutImageBtn);
        imageView = (ImageView) this.findViewById(R.id.imageview);
        selectImageBtn.setOnClickListener(this);
        cutImageBtn.setOnClickListener(this);
        // imageView.setImageBitmap(bm);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            // 处理图片按照手机的屏幕大小显示
            if (requestCode == IMAGE_SELECT) {
                Uri uri = data.getData();// 获得图片的路径
                int dw = getWindowManager().getDefaultDisplay().getWidth();// 获得屏幕的宽度
                int dh = getWindowManager().getDefaultDisplay().getHeight() / 2;
                try {
                    // 实现对图片的裁剪的类,是一个匿名内部类
                    BitmapFactory.Options factory = new BitmapFactory.Options();
                    factory.inJustDecodeBounds = true;// 如果设置为true,允许查询图片不是按照像素分配给内存
                    Bitmap bmp = BitmapFactory.decodeStream(
                            getContentResolver().openInputStream(uri), null,
                            factory);
                    // 对图片的宽度和高度对应手机的屏幕进行匹配
                    int hRatio = (int) Math
                            .ceil(factory.outHeight / (float) dh);
                    // 如果大于1 表示图片的高度大于手机屏幕的高度
                    int wRatio = (int) Math.ceil(factory.outWidth / (float) dw);
                    // 如果大于1 表示图片的宽度大于手机屏幕的宽度
                    // 缩放到1/radio的尺寸和1/radio^2像素
                    if (hRatio > 1 || wRatio > 1) {
                        if (hRatio > wRatio) {
                            factory.inSampleSize = hRatio;
                        } else {
                            factory.inSampleSize = wRatio;
                        }
                    }
                    // 对
                    factory.inJustDecodeBounds = false;
                    // 使用BitmapFactory对图片进行适屏的操作,
                    bmp = BitmapFactory.decodeStream(getContentResolver()
                            .openInputStream(uri), null, factory);
                    imageView.setImageBitmap(bmp);
                } catch (Exception e) {
                    // TODO: handle exception
                }
                // 表示裁剪图片
            } else if (requestCode == IMAGE_CUT) {
                Bitmap bitmap = data.getParcelableExtra("data");
                imageView.setImageBitmap(bitmap);
            }
        }
    }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.selectImageBtn:
            // 如何提取手机的图片的,并且进行选择图片的功能
            Intent intent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 打开手机的图片库
            startActivityForResult(intent, IMAGE_SELECT);
            break;
 
        case R.id.cutImageBtn:
            Intent intent2 = getImageClipIntent();
            startActivityForResult(intent2, IMAGE_CUT);
            break;
        }
    }
    private Intent getImageClipIntent() {
        // TODO Auto-generated method stub
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        // 实现对图片的裁剪,必须要设置图片的属性和大小
        intent.setType("image/*");// 获取任意的图片类型
        intent.putExtra("crop", "true");// 滑动选中图片区域
        intent.putExtra("aspectX", 1);// 表示剪切框的比例1:1的效果
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 80);// 指定输出图片的大小
        intent.putExtra("outputY", 80);
        intent.putExtra("return-data", true);
        return intent;
    }
}
·ImageView2:从网络上获取ImageView显示在本地
·1.编写HttpUtils.java类
package com.android.myhttp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtils {
    private final static String URL_PATH = "http://192.168.0.102:8080/myhttp/koala.jpg";// 访问网路图片的路径
    public HttpUtils() {
        // TODO Auto-generated constructor stub
    }
    /**
     * 从网络中获取图片信息,以流的形式返回
     * 
     * @return
     */
    public static InputStream getImageViewInputStream() throws IOException {
        InputStream inputStream = null;
 
        URL url = new URL(URL_PATH);
        if (url != null) {
            HttpURLConnection httpURLConnection = (HttpURLConnection) url
                    .openConnection();
            httpURLConnection.setConnectTimeout(3000);// 设置连接超时的时间
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoInput(true);
            int response_code = httpURLConnection.getResponseCode();
            if (response_code == 200) {
                inputStream = httpURLConnection.getInputStream();
            }
        }
        return inputStream;
    }
    /**
     * 从网络中获取图片信息,以字节数组的形式返回
     * 
     * @return
     */
    public static byte[] getImageViewArray() {
        byte[] data = null;
        InputStream inputStream = null;
        // 不需要关闭的输出流,直接写入到内存中
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 
        try {
            URL url = new URL(URL_PATH);
            if (url != null) {
                HttpURLConnection httpURLConnection = (HttpURLConnection) url
                        .openConnection();
                httpURLConnection.setConnectTimeout(3000);// 设置连接超时的时间
                httpURLConnection.setRequestMethod("GET");// 请求方法
                httpURLConnection.setDoInput(true);// 打开输入流
                int response_code = httpURLConnection.getResponseCode();
                int len = 0;
                byte[] b_data = new byte[1024];
 
                if (response_code == 200) {
                    inputStream = httpURLConnection.getInputStream();
                    while ((len = inputStream.read(b_data)) != -1) {
                        outputStream.write(b_data, 0, len);
                    }
                    data = outputStream.toByteArray();
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return data;
    }
}
·2.Main.java
package com.android.myhttp;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageView;
public class Main extends Activity {
    /** Called when the activity is first created. */
    private Button button;
    private ImageView imageView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button = (Button) this.findViewById(R.id.button);
        imageView = (ImageView) this.findViewById(R.id.imageview);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // try {
                // InputStream inputStream = HttpUtils
                // .getImageViewInputStream();
                // Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                // imageView.setImageBitmap(bitmap);
                // } catch (IOException e) {
                // // TODO: handle exception
                // }
                byte[] data = HttpUtils.getImageViewArray();
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
                        data.length);
                imageView.setImageBitmap(bitmap);
            }
        });
    }
}
·DatePicker和TimePicker
datePicker.init(2001, 1, 25, this);// 初始化日期
timePicker.setIs24HourView(true);// 显示时间是否是按照24小时制
timePicker.setOnTimeChangedListener(this);// 注册事件
// 时间控件的触发
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
    // TODO Auto-generated method stub
    Toast.makeText(Main.this,
            "hourOfDay:" + hourOfDay + "minute:" + minute, 1).show();
}
// 日期控件的触发
public void onDateChanged(DatePicker view, int year, int monthOfYear,
        int dayOfMonth) {
    // TODO Auto-generated method stub
    Calendar calendar = Calendar.getInstance();
    calendar.set(datePicker.getYear(), datePicker.getMonth(),
            datePicker.getDayOfMonth(), timePicker.getCurrentHour(),
            timePicker.getCurrentMinute());
    SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日    HH:mm");
    textView.setText(format.format(calendar.getTime()));
}
·
·
·
·
·点此进入下篇:

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试