TextView - setCustomSelectionActionModeCallback 如何为多个 TextView 选择文本时创建 ActionMode.Callback

TextView - setCustomSelectionActionModeCallback how create ActionMode.Callback for when the text is selected to many TextView

我的系统中有几个 TextView,其中大部分我必须调用我的自定义 ActionMode.Callback

问题是如何创建带有自定义 ActionMode.Callback 的 TextView?

今天我的代码就是这样

mTxOne.setCustomSelectionActionModeCallback(new MarkTextSelectionActionModeCallback());
 mTxTwo.setCustomSelectionActionModeCallback(new MarkTextSelectionActionModeCallback());
...

试试这个:

 public class CustomActionModeTextView extends TextView{

       //...implement your constructors as you may want to use...//
       @Override
       public ActionMode.Callback getCustomSelectionActionModeCallback (){
          return new MarkTextSelectionActionModeCallback();
        }


 }

创建您自己的 TextView 并将方法 getCustomSelectionActioModeCallback 覆盖为 return 始终是自定义操作模式回调的实例。这样您就不必每次都在视图中设置它。

记得

  • 在 XML 布局文件中使用自定义 class;
  • 投射时,投射到您的自定义 class 而不是 TextView;
  • 您可能想考虑在 class 中保留对自定义回调的引用。您可以在 constructor 和 return 期间在 get 方法中初始化它。这只是为了避免在每次方法调用时创建新实例。
public class TextViewA extends TextView {

    @Override
    protected void onCreateContextMenu(ContextMenu menu) {
        super.onCreateContextMenu(menu);
        setCustomSelectionActionModeCallback(new MarkTextSelectionActionModeCallback());
    }



public TextViewA(Context context) {
    super(context);
}
public TextViewA(Context context,AttributeSet attrs) {
    super(context,attrs);
}
public TextViewA(Context context, AttributeSet attrs, int defStyle){
    super(context, attrs, defStyle);
}

这里是xml

 <RelativeLayout      xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

  <br.com.vrbsm.textviewexample.TextViewA
      android:id="@+id/textView2" 
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textIsSelectable="true"
      android:textSize="12dp"
      />
</RelativeLayout>

这里主要

public class MainActivity extends Activity{
//  
    private TextViewA textview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        textview = (TextViewA)findViewById(R.id.textView2);
        textview.setText("Android is crazy");

    }


public class MarkTextSelectionActionModeCallback implements Callback {
.
.
.}