[기계적 인조 인간] 문자열 리소스에서 AlertDialog에서 클릭 가능한 하이퍼 링크를 얻으려면 어떻게해야합니까?
대화 상자에 일부 텍스트와 URL 만 표시하는 경우 솔루션이 더 간단 할 수 있습니다.
public static class MyOtherAlertDialog {
public static AlertDialog create(Context context) {
final TextView message = new TextView(context);
// i.e.: R.string.dialog_message =>
// "Test this dialog following the link to dtmilano.blogspot.com"
final SpannableString s =
new SpannableString(context.getText(R.string.dialog_message));
Linkify.addLinks(s, Linkify.WEB_URLS);
message.setText(s);
message.setMovementMethod(LinkMovementMethod.getInstance());
return new AlertDialog.Builder(context)
.setTitle(R.string.dialog_title)
.setCancelable(true)
.setIcon(android.R.drawable.ic_dialog_info)
.setPositiveButton(R.string.dialog_action_dismiss, null)
.setView(message)
.create();
}
}
여기에 표시된대로 http://picasaweb.google.com/lh/photo/up29wTQeK_zuz-LLvre9wQ?feat=directlink
대화 상자에서 메시지의 형식을 크게 변경하기 때문에 현재 가장 인기있는 답변이 마음에 들지 않았습니다.
다음은 텍스트 스타일을 변경하지 않고 대화 텍스트를 연결하는 솔루션입니다.
// Linkify the message
final SpannableString s = new SpannableString(msg); // msg should have url to enable clicking
Linkify.addLinks(s, Linkify.ALL);
final AlertDialog d = new AlertDialog.Builder(activity)
.setPositiveButton(android.R.string.ok, null)
.setIcon(R.drawable.icon)
.setMessage( s )
.create();
d.show();
// Make the textview clickable. Must be called after show()
((TextView)d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
-------------------이렇게하면 <a href>
태그도 강조 표시됩니다. emmby의 코드에 몇 줄을 추가했습니다. 그래서 그에게 신용
final AlertDialog d = new AlertDialog.Builder(this)
.setPositiveButton(android.R.string.ok, null)
.setIcon(R.drawable.icon)
.setMessage(Html.fromHtml("<a href=\"http://www.google.com\">Check this link out</a>"))
.create();
d.show();
// Make the textview clickable. Must be called after show()
((TextView)d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
-------------------실제로 모든 뷰를 처리하지 않고 단순히 문자열을 사용하려는 경우 가장 빠른 방법은 메시지 텍스트 뷰를 찾아 연결하는 것입니다.
d.setMessage("Insert your cool string with links and stuff here");
Linkify.addLinks((TextView) d.findViewById(android.R.id.message), Linkify.ALL);
-------------------JFTR, 여기에 내가 알아 낸 해결책이 있습니다.
View view = View.inflate(MainActivity.this, R.layout.about, null);
TextView textView = (TextView) view.findViewById(R.id.message);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(R.string.Text_About);
new AlertDialog.Builder(MainActivity.this).setTitle(
R.string.Title_About).setView(view)
.setPositiveButton(android.R.string.ok, null)
.setIcon(R.drawable.icon).show();
Android 소스에서 조각으로 빌린 해당 about.xml은 다음과 같습니다.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:paddingTop="2dip"
android:paddingBottom="12dip" android:paddingLeft="14dip"
android:paddingRight="10dip">
<TextView android:id="@+id/message" style="?android:attr/textAppearanceMedium"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:padding="5dip" android:linksClickable="true" />
</ScrollView>
중요한 부분은 linksClickable을 true로 설정하고 setMovementMethod (LinkMovementMethod.getInstance ())를 설정하는 것입니다.
-------------------대신에 ...
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle(R.string.my_title);
dialogBuilder.setMessage(R.string.my_text);
... 이제 다음을 사용합니다.
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle(R.string.my_title);
TextView textView = new TextView(this);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(R.string.my_text);
dialogBuilder.setView(textView);
-------------------가장 간단한 방법 :
final AlertDialog dlg = new AlertDialog.Builder(this)
.setTitle(R.string.title)
.setMessage(R.string.message)
.setNeutralButton(R.string.close_button, null)
.create();
dlg.show();
// Important! android.R.id.message will be available ONLY AFTER show()
((TextView)dlg.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
-------------------위의 모든 대답은 주어진 문자열에 html 태그가 포함되어 있으면 모든 태그를 제거하려고 시도한 등의 html 태그를 제거하지 않을 것입니다.
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setTitle("Title");
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, null);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setMovementMethod(LinkMovementMethod.getInstance());
text.setText(Html.fromHtml("<b>Hello World</b> This is a test of the URL <a href=http://www.example.com> Example</a><p><b>This text is bold</b></p><p><em>This text is emphasized</em></p><p><code>This is computer output</code></p><p>This is<sub> subscript</sub> and <sup>superscript</sup></p>";));
builder.setView(layout);
AlertDialog alert = builder.show();
custom_dialog는 다음과 같습니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF"
/>
</LinearLayout>
위의 코드는 모든 html 태그를 제거하고 지정된 html 형식화 텍스트의 다른 모든 경우를 클릭 가능 URL로 예제로 표시합니다.
-------------------현재 답변에별로 만족스럽지 않았습니다. AlertDialog를 사용하여 href 스타일의 클릭 가능한 하이퍼 링크를 원할 때 중요한 두 가지가 있습니다.
- 보기
setMessage(…)
만 클릭 가능한 HTML 콘텐츠를 허용하므로 콘텐츠를를 사용 하지 않고보기로 설정합니다. - 올바른 이동 방법 설정 (
setMovementMethod(…)
)
다음은 작동하는 최소한의 예입니다.
strings.xml
<string name="dialogContent">
Cool Links:\n
<a href="http://stackoverflow.com">Stackoverflow</a>\n
<a href="http://android.stackexchange.com">Android Enthusiasts</a>\n
</string>
MyActivity.java
…
public void showCoolLinks(View view) {
final TextView textView = new TextView(this);
textView.setText(R.string.dialogContent);
textView.setMovementMethod(LinkMovementMethod.getInstance()); // this is important to make the links clickable
final AlertDialog alertDialog = new AlertDialog.Builder(this)
.setPositiveButton("OK", null)
.setView(textView)
.create();
alertDialog.show()
}
…
-------------------많은 질문과 답변을 확인했지만 작동하지 않습니다. 내가 직접했다. 이것은 MainActivity.java의 코드 조각입니다.
private void skipToSplashActivity()
{
final TextView textView = new TextView(this);
final SpannableString str = new SpannableString(this.getText(R.string.dialog_message));
textView.setText(str);
textView.setMovementMethod(LinkMovementMethod.getInstance());
....
}
이 태그를 res \ values \ String.xml에 넣습니다.
<string name="dialog_message"><a href="http://www.nhk.or.jp/privacy/english/">NHK Policy on Protection of Personal Information</a></string>
-------------------을 사용하는 DialogFragment
경우이 솔루션이 도움이 될 것입니다.
public class MyDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// dialog_text contains "This is a http://test.org/"
String msg = getResources().getString(R.string.dialog_text);
SpannableString spanMsg = new SpannableString(msg);
Linkify.addLinks(spanMsg, Linkify.ALL);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.dialog_title)
.setMessage(spanMsg)
.setPositiveButton(R.string.ok, null);
return builder.create();
}
@Override
public void onStart() {
super.onStart();
// Make the dialog's TextView clickable
((TextView)this.getDialog().findViewById(android.R.id.message))
.setMovementMethod(LinkMovementMethod.getInstance());
}
}
-------------------위에서 설명한 옵션 중 일부를 결합하여 저에게 적합한이 기능을 찾았습니다. 결과를 대화 상자 작성기의 SetView () 메서드에 전달합니다.
public ScrollView LinkifyText(String message)
{
ScrollView svMessage = new ScrollView(this);
TextView tvMessage = new TextView(this);
SpannableString spanText = new SpannableString(message);
Linkify.addLinks(spanText, Linkify.ALL);
tvMessage.setText(spanText);
tvMessage.setMovementMethod(LinkMovementMethod.getInstance());
svMessage.setPadding(14, 2, 10, 12);
svMessage.addView(tvMessage);
return svMessage;
}
-------------------나를 위해 개인 정보 보호 정책 대화 상자를 만드는 가장 좋은 솔루션은 다음과 같습니다.
private void showPrivacyDialog() {
if (!PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean(PRIVACY_DIALOG_SHOWN, false)) {
String privacy_pol = "<a href='https://sites.google.com/view/aiqprivacypolicy/home'> Privacy Policy </a>";
String toc = "<a href='https://sites.google.com/view/aiqprivacypolicy/home'> T&C </a>";
AlertDialog dialog = new AlertDialog.Builder(this)
.setMessage(Html.fromHtml("By using this application, you agree to " + privacy_pol + " and " + toc + " of this application."))
.setPositiveButton("ACCEPT", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putBoolean(PRIVACY_DIALOG_SHOWN, true).apply();
}
})
.setNegativeButton("DECLINE", null)
.setCancelable(false)
.create();
dialog.show();
TextView textView = dialog.findViewById(android.R.id.message);
textView.setLinksClickable(true);
textView.setClickable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
작동 예 확인 : 앱 링크
-------------------XML 리소스에 경고 상자를 지정하고로드하여이를 수행합니다. 예를 들어 ChandlerQE.java 끝 근처에서 인스턴스화 되는 about.xml (ABOUT_URL ID 참조)을 참조하십시오 . 자바 코드의 관련 부분 :
LayoutInflater inflater =
(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = (View) inflater.inflate(R.layout.about, null);
new AlertDialog.Builder(ChandlerQE.this)
.setTitle(R.string.about)
.setView(view)
-------------------이것이 내 해결책입니다. html 태그가 포함되지 않고 URL이 표시되지 않는 일반 링크를 생성합니다. 또한 디자인을 그대로 유지합니다.
SpannableString s = new SpannableString("This is my link.");
s.setSpan(new URLSpan("http://www.google.com"), 11, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
final AlertDialog d = builder
.setPositiveButton("CLOSE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing, just close
}
})
.setNegativeButton("SHARE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Share the app
share("Subject", "Text");
}
})
.setIcon(R.drawable.photo_profile)
.setMessage(s)
.setTitle(R.string.about_title)
.create();
d.show();
((TextView)d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
-------------------가장 쉽고 짧은 방법은 이렇게
대화 상자의 Android 링크
((TextView) new AlertDialog.Builder(this)
.setTitle("Info")
.setIcon(android.R.drawable.ic_dialog_info)
.setMessage(Html.fromHtml("<p>Sample text, <a href=\"http://google.nl\">hyperlink</a>.</p>"))
.show()
// Need to be called after show(), in order to generate hyperlinks
.findViewById(android.R.id.message))
.setMovementMethod(LinkMovementMethod.getInstance());
-------------------이것은 내가 사용하는 간단한 방법입니다
strings.xml의 문자열
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
<string name="credits_title">Credits</string>
<string name="confirm">OK</string>
<string name="credits">All rights reserved.
<a href="https://google.com">Source</a>
</string>
</resources>
dimens.xml의 치수
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
<dimen name="margin_8dp">8dp</dimen>
<dimen name="margin_32dp">32dp</dimen>
</resources>
도우미 대화 클래스
public class MessageHelper {
public static void showCreditsDialog(Context context) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(R.string.credits_title);
TextView textView = new TextView(context);
int padding = (int) context.getResources().getDimension(R.dimen.margin_32dp);
int topPadding = (int) context.getResources().getDimension(R.dimen.margin_8dp);
textView.setPadding(padding, topPadding, padding, 0);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(R.string.credits);
alertDialog.setView(textView);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, context.getResources().getString(R.string.confirm),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
사용하는 방법
MessageHelper.showCreditsDialog(this); // this is the context
시사
쉬운 Kotlin 구현
문자열 리소스 :
<string name="foo"><a href="https://www.google.com/">some link</a></string>
암호:
AlertDialog.Builder(context)
.setMessage(R.string.foo)
.show()
.apply {
findViewById<TextView>(android.R.id.message)
?.movementMethod = LinkMovementMethod.getInstance()
}
출처
https://stackoverflow.com/questions/2005856