如何灵活地在此代码中使用if语句?

时间:2014-04-01 09:44:15

标签: android api copy

我有这个代码用于复制到剪贴板的API< 11

在我的 onCreate 方法中:

TextView textView=(TextView)findViewById(R.id.textView1);
registerForContextMenu(textView);

然后覆盖 onCreateContextMenu

@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    //user has long pressed your TextView
    menu.add(0, v.getId(), 0, "Copy");

    //cast the received View to TextView so that you can get its text
    TextView textView = (TextView) v;

    //place your TextView's text in clipboard
    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
    clipboard.setText(textView.getText()); }

 " android:textIsSelectable="true" " ,  for API >= 11 , 

我如何使用if语句,如果用户的移动设备是 API< 11 第一个代码运行,否则第二个运行?????

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你需要这样的东西:

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressWarnings("deprecation")
public void copyToClipboard(String label, String text)
{
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        // Here we go if the device API level is less than 11, 
        // so we use old ClipboardManager class from "android.text" package
        android.text.ClipboardManager clipboard
                = (android.text.ClipboardManager) 
                getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(text);
    } else {
        // Here we go if the device API highter than 11, 
        // so we use new ClipboardManager class from "android.content" package
        android.content.ClipboardManager clipboard
                = (android.content.ClipboardManager) 
                getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText(label, text);
        clipboard.setPrimaryClip(clip);
    }
}

Build.VERSION_CODES.HONEYCOMB对应于API级别11.此功能使用旧API级别11上的旧API和API级别11之外的设备上的新API将文本复制到剪贴板。

使用代码的函数使用示例:

@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
    //user has long pressed your TextView
    menu.add(0, v.getId(), 0, "Copy");

    //cast the received View to TextView so that you can get its text
    TextView textView = (TextView) v;

    //place your TextView's text in clipboard
    copyToClipboard("Label describing text", textView.getText().toString());
}

当然,在使用copyToClipboard函数之前,您必须将其复制到您的Activity类中。