EditText的長按事件會自動彈出上下文菜單,其中有“選擇文字”“複製”“粘貼”等功能選項,想讓TextView也具有這樣的功能,經研究,EditText就是繼承於TextView而來的,在TextView的源碼中就存在“選擇文字”“複製”“粘貼”等功能的代碼,(但是爲什麼在佈局中添加<TextView />組件卻不能直接使用這些功能呢,尚有待研究),我發現一種簡單方法可以使EditText“變成”具有“選擇文字”“複製”“粘貼”等功能的“TextView”,在佈局文件中這樣寫(注意:一定要寫上粗體的那幾句代碼):
<EditText
android:editable="false"
android:gravity="top"
android:background="#030303"
android:textColor="#FFFFFF"
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="sdfsdaddfsfsf "
/>
這樣設置的EditText運行後展現出來的就像是一個TextView了(如下圖。但是有個光標會在一直閃)
如果在書寫代碼時感覺用EditText當TextView很奇怪,可以自定義一個View繼承於EditText,比如:
package com.test;
public class MyTextView extends EditText {
public MyTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
@Override
protected boolean getDefaultEditable() {//等同於在佈局文件中設置
android:editable="false"
return false;
}
}
在佈局文件中則寫爲:
<com.test.MyTextView
android:background="#030303"
android:textColor="#FFFFFF"
android:gravity="top"
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="sdfsdaddfsfsf"
/>
-------------------------------------------------------------------------------------------------
以上方法雖然實現了文本的選擇、複製等功能,但是感覺使用起來不方便,需要長按組件,在彈出的上下文菜單中選擇“選擇文本”,然後再去選中想要的字,這一系列的操作比較繁瑣,用戶體驗不是很好。
下面再來研究一個比較靈活的自定義TextView的實現,可以直接選中文本的。
-------------------------------------------------------------------------------------------------
此效果的實現需要兩個步驟:
1.選擇 文本:
(有待研究)
有一個 Selection 類~
2.設置到剪貼板中:
android的剪貼板功能,比如將文本複製到剪貼板或者從剪貼板複製數據等操作。使用起來很簡單,系統給我們提供了很方便的接口,如下所示:
//獲取剪貼板管理服務
ClipboardManager cm =(ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
//將文本數據複製到剪貼板
cm.setText(message);
//讀取剪貼板數據(EditText的長按事件會自動彈出上下文菜單,其中有“粘貼”的功能選項,應該是調用了下面的方法獲得要粘貼的數據。這個粘貼的功能系統已經實現了,不需要我們自己調用了。)
cm.getText();