链接警报对话框片段

时间:2015-03-28 17:02:08

标签: android

我使用此代码显示带链接的简单对话框:

  String msg = "http://www.google.com"
  final SpannableString s = new SpannableString(msg);
  Linkify.addLinks(s, Linkify.ALL);
  Fragment dialogFrag = MyDialogFragment.newInstance(title, msg);
  getFragmentManager().beginTransaction().add(dialogFrag, key).commit();

MyDialogFragment类:

public class MyDialogFragment extends DialogFragment {

public static MyDialogFragment newInstance(String title, String message) {
    MyDialogFragment frag = new MyDialogFragment();
    Bundle args = new Bundle();
    args.putString("title", title);
    args.putString("msg", message);
    frag.setArguments(args);
    return frag;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    String title = getArguments().getString("title");
    String msg = getArguments().getString("msg");

    return new AlertDialog.Builder(getActivity())
            .setTitle(title)
            .setMessage(msg)
            .setPositiveButton(android.R.string.ok, null)
            .create();
}
}

对话框不显示超链接。我没有支持库使用android 5.0.1。

2 个答案:

答案 0 :(得分:0)

构建包含TextView消息的SpannableString

String title = getArguments().getString("title");
String msg = getArguments().getString("msg");

final TextView textView = new TextView(getActivity());
final SpannableString spannableMsg = new SpannableString(msg);

Linkify.addLinks(spannableMsg, Linkify.WEB_URLS);

textView.setText(spannableMsg);
textView.setMovementMethod(LinkMovementMethod.getInstance());

并添加TextView而不是分配文字:

return new AlertDialog.Builder(getActivity())
        .setTitle(title)
        .setView(textView)
        .setPositiveButton(android.R.string.ok, null)
        .create();

答案 1 :(得分:0)

随着时间的推移,向查询添加一些更新的输入。

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
   super.onViewCreated(view, savedInstanceState)
   setupView(view)
}    
    
private fun setupView(view: View) {
   toolbar.setNavigationOnClickListener({ v -> dismiss() })
   toolbar.title = "New Message"
   view.tvTitle.text = arguments?.getString("title")
   view.tvBody.autoLinkMask = Linkify.ALL
   view.tvBody.text = arguments?.getString("body")
   view.tvBody.movementMethod = LinkMovementMethod.getInstance()
}

最重要的 2 个步骤是:

  1. 链接
  2. setMovementMethod

此后所有链接都可以正常工作。