★15.基本视图

View

获取视图宽高

int width = view.getWidth();
int height = view.getHeight();
if (width == 0 && height == 0) {
    view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            int width = view.getWidth();
            int height = view.getHeight();
            // width和height有效
        }
    });
} else {
    // width和height有效
}

监听 PreDraw 阶段

mView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        mView.getViewTreeObserver().removeOnPreDrawListener(this);
        // Todo: do something
        return true;
    }
});

注意选项

  • 设备配置改变时,具有ID属性的View可以保存运行状态。
  • 注意getWidth()getHeight()只有在onCreate()onStart()onResume()之后才有大小,否则返回0

TextView


EditText

代码


TextWatcher

textView.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) { }
});

AutoCompleteTextView

String[] strArr = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, strArr);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.txt);

// 设置预测的最小字母数
textView.setThreshold(3);
textView.setAdapter(adapter);

ImageView

简单示例


设置图片

  • 使用setImageDrawable()setImageBitmap()来设置图片。

Button

简单示例

相关工具

  • 生成工具:Android Button Maker

ImageButton


ToggleButton


ToggleButton toggleButton = (ToggleButton) v.findViewById(R.id.toggleButton);
toggleButton.setOnClickListener(view -> {
    if (((ToggleButton) view).isChecked())
        Log.d("TAG", "isChecked");
    else
        Log.d("TAG", "notChecked");
});

CheckBox


CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox);
checkBox.setOnClickListener(view -> {
    if (((CheckBox) view).isChecked())
        Log.d("TAG", "isChecked");
    else
        Log.d("TAG", "notChecked");
});

RadioGroup、RadioButton



    

    

RadioGroup view = (RadioGroup) v.findViewById(R.id.radioGroup);
view.setOnCheckedChangeListener((radioGroup, i) -> {
    RadioButton radioButton = (RadioButton) radioGroup.findViewById(R.id.radioButton1);
    if (radioButton.isChecked())
        Log.d("TAG", "isChecked");
    else
        Log.d("TAG", "notChecked");
});

ProgressBar


ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
progressBar.setMax(200);
progressBar.setProgress(100);

TimePicker

xml


代码

TimePicker timePicker = (TimePicker) itemView.findViewById(R.id.timePicker);
timePicker.setIs24HourView(true);

DatePicker

xml


代码

mDatePicker.init(year, month, day, null);

你可能感兴趣的:(★15.基本视图)