2013-12-19 63 views

回答

0

在Android 3.0及以上版本中,默認情況下可以使用WebView中的複製功能。要在3.0以下版本中啓用複製功能,需要添加一些代碼。我做的第一件事是在視圖的底部添加一個複製按鈕到我的Actionbar

退房的Copy Text in a WebView in Android

下面是展示如何使用代碼:

public class TryDemoActivity extends Activity implements 
OnClickListener { 
    private WebView webview1; 
    private Button copyButton; 
    private Button pasteButton; 
    private Button highlightButton; 
    private ClipboardManager clipboard; 
    /** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    webview1 = (WebView) findViewById(R.id.webview); 
    copyButton = (Button) findViewById(R.id.copy); 
    pasteButton = (Button) findViewById(R.id.paste); 

    webview1.loadUrl("file:///android_asset/1.1.html"); 
    clipboard =(ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
    copyButton.setOnClickListener(this); 
    pasteButton.setOnClickListener(this); 
} 
private void emulateShiftHeld(WebView view) 
{ 
    try 
    { 
     KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, 
KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0); 
    shiftPressEvent.dispatch(view); 

    registerForContextMenu(view); 
    Toast.makeText(this, "select_text_now", Toast.LENGTH_SHORT).show(); 

    } 
    catch (Exception e) 
    { 
     Log.e("dd", "Exception in emulateShiftHeld()", e); 
    } 
} 
@Override 
public void onClick(View v) { 
    switch(v.getId()) 
    { 
     case R.id.copy: 
      emulateShiftHeld(webview1); 
     break; 
     case R.id.paste: 
     Toast.makeText(this, clipboard.getText(),Toast.LENGTH_SHORT).show(); 
     break; 
    } 
    } 
} 

編輯:

注:代碼emulateShiftHeld這是在棄用4.0,這可能是爲什麼它工作在2.2而不是4.0。

退房的Post,我發現HERE

+0

謝謝4回答。但在Android 4.0中,不允許我選擇。 – nil

+0

看看我更新的答案。 – GrIsHu