android-Spannable字符串错误
作者:互联网
我正在尝试在警报对话框中以超链接形式显示一些文本.该过程的一部分要求我使用SpannableString格式化某些文本.问题是我的应用程序在代码的SpannableString部分遇到了运行时错误.
TextView Tv= (TextView) findViewById(R.id.textView3);
SpannableString s = new SpannableString("www.google.com");
Linkify.addLinks(s, Linkify.WEB_URLS);
Tv.setText(s);
Tv.setMovementMethod(LinkMovementMethod.getInstance());
我查看了DDMS,错误显示Java.Lang.NullPointerException.有人经历过吗?我应该能够将SpannableString方法传递给硬编码的字符串.我不知道为什么它会像这样崩溃.
这是我的java文件中的OnCreate函数:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//System.out.println("+++++++++++++++++++++++");
TextView Tv= (TextView) findViewById(R.id.textviewH);
Tv.setText("GO!");
//System.out.println("+++++++++++++++++++++++");
SpannableString s = new SpannableString("www.google.com");
Linkify.addLinks(s, Linkify.WEB_URLS);
Tv.setText(s);
Tv.setMovementMethod(LinkMovementMethod.getInstance());
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("About T2M");
dialog.setIcon(R.drawable.ic_launcher);
dialog.setView(getLayoutInflater().inflate(R.layout.activity_about_t2m, null));
dialog.setCancelable(false);
dialog.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
//System.out.println("+++++++++++++++++++++++");
dialog.create();
dialog.show();
}
这是我的XML文件中的文本视图:
<TextView
android:id="@+id/textviewH"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView5"
android:layout_alignLeft="@+id/textView2"
android:autoLink="all"
android:clickable="true"
android:text="Humium"
android:textSize="15sp" />
解决方法:
好的,所以我认为问题出在通货膨胀过程中.
看来您在膨胀Layout之前正在尝试访问TextView.因此findViewById不会找到任何内容,因为它将在“活动布局”中进行搜索.
这里的窍门是首先给您的自定义布局充气(这是您可以做的一个例子:
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
//Inflating the custom Layout
View view = LayoutInflater.from(this).inflate(R.layout.activity_about_t2m, null);
//Searching for the TextView in it
TextView tv = (TextView)view.findViewById(R.id.textviewH);
//Then making the links
SpannableString s = new SpannableString("www.google.fr");
Linkify.addLinks(s, Linkify.WEB_URLS);
//Adding the text to the View and make the links clickable
tv.setText(s);
tv.setMovementMethod(LinkMovementMethod.getInstance());
//Finally applying the custom view we inflated (R.layout.activity_about_t2m) on the AlertDialog and ....
dialog.setView(view);
dialog.setTitle("About T2M");
dialog.setIcon(R.drawable.ic_launcher);
dialog.setCancelable(false);
dialog.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
}
);
编辑1:
我在这个示例中犯了一个错误…在您的情况下,getApplicationContext()应该是这个(我在代码中进行了修复)
更多信息在这里:
Android – Linkify Problem
编辑2:
好的,现在应该可以理解了吗?
标签:android,spannablestring,spannable 来源: https://codeday.me/bug/20191011/1890219.html