Android开发: Java文件中操作基础UI组件

发布于:2025-03-29 ⋅ 阅读:(38) ⋅ 点赞:(0)

Android Java文件中基础UI组件操作指南

一、常用UI组件基本操作

1. TextView文本控件

TextView textView = findViewById(R.id.textView);

// 设置文本内容
textView.setText("欢迎使用Android");

// 设置文本颜色
textView.setTextColor(Color.BLUE);  // 使用Color类常量
textView.setTextColor(getResources().getColor(R.color.my_color));  // 使用资源颜色

// 设置文本大小
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);  // 18sp

// 设置字体样式
textView.setTypeface(null, Typeface.BOLD_ITALIC);  // 加粗斜体

// 设置超链接
textView.setMovementMethod(LinkMovementMethod.getInstance());
String htmlText = "<a href='https://www.example.com'>访问网站</a>";
textView.setText(Html.fromHtml(htmlText));

2. EditText输入框

EditText editText = findViewById(R.id.editText);

// 设置输入提示
editText.setHint("请输入用户名");

// 设置输入类型
editText.setInputType(InputType.TYPE_CLASS_TEXT);  // 普通文本
editText.setInputType(InputType.TYPE_CLASS_NUMBER);  // 纯数字
editText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);  // 密码
editText.setHint(getString(R.string.input_account)); // 设置提示文本

// 获取输入内容
String input = editText.getText().toString().trim();

// 添加输入监听
editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // 实时处理输入变化
    }
    
    @Override
    public void afterTextChanged(Editable s) {}
});

3. Button按钮

Button button = findViewById(R.id.button);
button .setText(getString(R.string.login)); // 设置按钮的文本
// 点击事件处理
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // 处理点击逻辑
        Toast.makeText(MainActivity.this, "按钮被点击", Toast.LENGTH_SHORT).show();
    }
});

// Java 8 Lambda简化写法
button.setOnClickListener(v -> {
    // 点击处理逻辑
});

// 设置按钮背景
button.setBackgroundResource(R.drawable.btn_selector);

// 禁用按钮
button.setEnabled(false);

二、选择类组件操作

1. CheckBox复选框

CheckBox checkBox = findViewById(R.id.checkBox);

// 设置选中状态
checkBox.setChecked(true);

// 状态变化监听
checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
    if(isChecked) {
        // 选中状态
    } else {
        // 未选中状态
    }
});

2. RadioGroup和RadioButton单选组

RadioGroup radioGroup = findViewById(R.id.radioGroup);
RadioButton radioButton1 = findViewById(R.id.radioButton1);
RadioButton radioButton2 = findViewById(R.id.radioButton2);

// 选中监听
radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
    if(checkedId == R.id.radioButton1) {
        // 选项1被选中
    } else if(checkedId == R.id.radioButton2) {
        // 选项2被选中
    }
});

// 获取选中项ID
int selectedId = radioGroup.getCheckedRadioButtonId();

3. Spinner下拉选择框

Spinner spinner = findViewById(R.id.spinner);

// 创建适配器
ArrayAdapter<String> adapter = new ArrayAdapter<>(
    this, 
    android.R.layout.simple_spinner_item, 
    new String[]{"选项1", "选项2", "选项3"}
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

// 选择监听
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String selected = parent.getItemAtPosition(position).toString();
    }
    
    @Override
    public void onNothingSelected(AdapterView<?> parent) {}
});

三、图片和进度显示组件

1. ImageView图片显示

ImageView imageView = findViewById(R.id.imageView);

// 设置本地图片资源
imageView.setImageResource(R.drawable.ic_launcher);

// 设置图片缩放类型
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

// 加载网络图片(使用Glide库)
Glide.with(this)
    .load("https://example.com/image.jpg")
    .placeholder(R.drawable.placeholder)  // 占位图
    .error(R.drawable.error)  // 错误图
    .into(imageView);

2. ProgressBar进度条

ProgressBar progressBar = findViewById(R.id.progressBar);

// 显示/隐藏进度条
progressBar.setVisibility(View.VISIBLE);  // 显示
progressBar.setVisibility(View.GONE);     // 隐藏

// 设置进度(适用于水平进度条)
progressBar.setProgress(50);  // 设置当前进度
progressBar.setMax(100);      // 设置最大值

// 不确定进度样式
progressBar.setIndeterminate(true);

3. SeekBar拖动条

SeekBar seekBar = findViewById(R.id.seekBar);

// 设置最大值和当前值
seekBar.setMax(100);
seekBar.setProgress(30);

// 进度变化监听
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        // 进度变化时实时回调
    }
    
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {}
    
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {}
});

四、布局容器操作

1. 动态添加视图到LinearLayout

LinearLayout container = findViewById(R.id.container);

// 创建新视图
Button newButton = new Button(this);
newButton.setText("动态添加的按钮");

// 设置布局参数
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(10, 10, 10, 10);  // 设置边距

// 添加视图到容器
container.addView(newButton, params);

2. 动态切换视图

FrameLayout frameLayout = findViewById(R.id.frameLayout);

// 显示第一个视图
View view1 = LayoutInflater.from(this).inflate(R.layout.view1, frameLayout, false);
frameLayout.addView(view1);

// 替换为第二个视图
View view2 = LayoutInflater.from(this).inflate(R.layout.view2, frameLayout, false);
frameLayout.removeAllViews();  // 移除所有子视图
frameLayout.addView(view2);

五、常用工具方法

1. Toast消息提示

// 简单Toast
Toast.makeText(this, "这是一个提示", Toast.LENGTH_SHORT).show();

// 自定义Toast
Toast toast = new Toast(this);
View view = LayoutInflater.from(this).inflate(R.layout.custom_toast, null);
toast.setView(view);
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

2. Snackbar提示条

Snackbar.make(findViewById(android.R.id.content), 
        "操作已完成", 
        Snackbar.LENGTH_LONG)
    .setAction("撤销", v -> {
        // 撤销操作
    })
    .show();

3. 弹出菜单

PopupMenu popupMenu = new PopupMenu(this, anchorView);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());

popupMenu.setOnMenuItemClickListener(item -> {
    switch(item.getItemId()) {
        case R.id.menu_item1:
            // 处理菜单项1
            return true;
        case R.id.menu_item2:
            // 处理菜单项2
            return true;
    }
    return false;
});

popupMenu.show();