Dynamic Resizing Android Studio TextView [ซ้ำ]
ฉันกำลังพยายามปรับขนาดกล่องข้อความแบบไดนามิกโดยใช้โค้ด Java ฉันต้องการให้ความกว้างไม่ใช้เนื้อหาตัด แต่ใช้ตัวเลขคงที่ใน dp ฉันต้องการให้ทำในโค้ด Java แทนไฟล์ XML ฉันต้องการให้เป็นเช่นนี้เพราะฉันต้องการนำไปใช้กับแต่ละรายการในมุมมองรีไซเคิล ต้องทำงานกับหน้าจอหลายขนาด มันจะทำงานเหมือนกับความยาวขั้นต่ำสำหรับขนาดกล่องข้อความ หากคุณรู้วิธีการทำเช่นนี้จะเป็นที่ชื่นชอบมาก
คำตอบ
สิ่งนี้เรียกว่าการปรับขนาดอัตโนมัติและสามารถทำได้โดยการเพิ่ม TextChangedListener ซึ่งเป็น Listener สำหรับ Edit Tex ผู้ฟังนี้จะดูการเปลี่ยนแปลงของ editText และมีสถานะที่แตกต่างกันสามสถานะ นอกจากนี้คุณสามารถสร้างส่วนประกอบ (มุมมองที่กำหนดเอง) และขยายจากชื่อ AppCompatTextView ได้ตามที่คุณต้องการ ในการเริ่มต้นคุณสามารถเพิ่มโค้ดด้านล่าง:
public class CustomTextView extends AppCompatTextView {
Context ctx;
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
ctx = context;
init();
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
ctx = context;
init();
}
public CustomTextView(Context context) {
super(context);
ctx = context;
init();
}
public void init() {
setOnTouchListener(null);
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) {
if (getText().toString().length() > 10){
setTextSize(TypedValue.COMPLEX_UNIT_SP, textSizeSmall);
}
else if (getText().toString().length() > 5){
setTextSize(TypedValue.COMPLEX_UNIT_SP, textSizeMedium);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
ตรวจสอบสิ่งเหล่านี้ด้วยมีเอกสารประกอบสำหรับ:
การสอนการปรับแต่งข้อความอัตโนมัติสำหรับ Android
การปรับขนาด TextViews อัตโนมัติ
ฉันคิดว่านี่จะช่วยคุณได้ ..
LinearLayout.LayoutParams textParam = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
textView.setLayoutParams(textParam);