問題描述
我的問題是,如何在 android 的 editBox 中放置標簽?
My question is, how to put a label in a editBox in android ?
例如,我想在聯系人選擇器的 editbox 中輸入To:",即使我按屏幕鍵盤上的退格鍵也不會被刪除.
Like for example, i want to put "To:" in editbox of a contact picker which will not get deleted even if I press backspace on the onscreen keyboard.
我嘗試使用 android:hint,但是當編輯框成為焦點或單擊時它會被刪除.
I tried with android:hint, but it gets deleted when the editBox is focus or clicked.
我嘗試了圖像,但看起來不太好.所以,我需要一種方法來實現這個標簽的東西.
I tried with image but it's not looking good. So, I need a method by which i can implement this label thing.
查看可視化圖
推薦答案
我給你兩個想法:
如果您只在幾個地方需要它,您可以使用 FrameLayout/merge 在您的 EditText 上添加一個 TextView.然后在編輯文本上使用填充,您可以使 TextView 看起來像是在 EditText內部".:
If you only need this in a couple of places, you can use a FrameLayout / merge to have a TextView over your EditText. Then using a padding on the edit text, you can make it seem like the TextView is "inside" the EditText. :
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="40dp" >
<requestFocus />
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="10dp"
android:text="To : " />
</FrameLayout>
否則,您可以通過編寫自己的類來實現自己的 EditText 版本.這是一個基本示例,您需要對其進行一些調整:
Else you can inplement your own version of EditText, by writing your own Class. Here's a basic example, you'd need to tweak it a little :
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.EditText;
public class LabelledEditText extends EditText {
public LabelledEditText(Context context) {
super(context);
mPaddingLeft = getPaddingLeft();
}
public LabelledEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mPaddingLeft = getPaddingLeft();
}
protected void onDraw(Canvas canvas) {
TextPaint textPaint = getPaint();
Rect size = new Rect();
textPaint.getTextBounds(mLabel, 0, mLabel.length(), size);
setPadding(mPaddingLeft + size.width(), getPaddingTop(), getPaddingRight(), getPaddingBottom());
super.onDraw(canvas);
canvas.drawText(mLabel, mPaddingLeft + size.left, size.bottom + getPaddingTop(), textPaint);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private String mLabel = "To : ";
private int mPaddingLeft;
}
這篇關于在android的編輯框中添加標簽的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!