2013-08-03 1 views
2

Я пытаюсь отобразить текст в диалоговом окне предупреждения как гиперссылку. Часть процесса требует от меня использовать SpannableString для форматирования текста. Проблема в том, что мое приложение испытывает ошибку времени выполнения в части SpannableString моего кода.Ошибка Spannable String

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 жестко закодированную строку. Я не знаю, почему он так разбивается.

Это OnCreate функция в моем файле Java:

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" /> 

My Layout

+0

Не могли бы вы предоставить нам строку, где возникает NullPointerException? – Aleks

+0

Я провел несколько тестов с использованием println и обнаружил, что ошибка происходит прямо на линии построения SpannableString. –

+1

Вы уверены, что это не могло произойти из ** findViewById **? Потому что я не могу думать о какой-либо причине, почему ** SpannableString ** будет искать исключение NullPointerException ... – Aleks

ответ

1

Хорошо, так что я думаю, что этот вопрос пришел от инфляционного процесса. Кажется, что вы пытаетесь получить доступ к TextView перед тем, как раздуть макет. Итак, findViewById ничего не найдет, поскольку он будет искать в макете активности.

Хитрость здесь будет надуть пользовательского макета первый (, вот Exemple того, что вы могли бы сделать:

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(); 
       } 
      } 
    ); 

Edit 1: Я сделал ошибку с этим примером ... В вашей случае getApplicationContext() должен быть это (я сделал исправления в коде)

Больше информации здесь: Android - Linkify Problem

Edit 2: Ok, так что теперь, что должно быть понятным право?

+0

Что вы будете делать с просмотром после его создания? Я не вижу, чтобы он использовался где-либо –

+0

Я нашел TextView внутри: TextView tv = (TextView) view.findViewById (R.id.text); – Aleks

+0

Хорошо, я попытаюсь это сделать –

1

Этот код работает отлично для меня. Надеюсь, это тоже поможет вам.

TextView richTextView = (TextView) findViewById(R.id.text_aboutus); 
    // this is the text we'll be operating on 
    SpannableString text = new SpannableString("Hi Click on Google.com and yahoo.com or Pmstudy.com"); 
    text.setSpan(
      new URLSpan("http://www.google.com/"), 
      13, 22, 0); 
    text.setSpan(new URLSpan("http://www.yahoo.com/"), 
      28, 36, 0); 
    text.setSpan(new URLSpan("http://www.pmstudy.com"), 41, 51, 0); 

    richTextView.setMovementMethod(LinkMovementMethod.getInstance()); 
    richTextView.setText(text, BufferType.SPANNABLE); 

Наслаждайтесь ......

Спасибо, Мукеш

+0

Я использую настраиваемый диалог оповещений. Как мне это сделать? –

1
**You can Use Same code in your custom Dialog as well. This is currently working for me. 

you need to inflate your custom-dialog-layout in your code .** 

custom_dialog.xml 

//this xml is for custom Dialog. 
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <TextView android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:id="@+id/text_aboutus" 
     android:text="Hi Click on Google.com and yahoo.com or Pmstudy.com"/> 

</LinearLayout> 



package PackageName; 

// import Files 

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

    Button show_dialog=(Button) findViewById(R.id.imgView); 
    show_dialog.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      Dialog d=new Dialog(MainActivity.this); 
      View v=getLayoutInflater().inflate(R.layout.custom_dialog, null); 
      TextView richTextView = (TextView) v.findViewById(R.id.text_aboutus); 
      SpannableString text = new SpannableString("Hi Click on Google.com and yahoo.com or Pmstudy.com"); 
      text.setSpan(
        new URLSpan("http://www.google.com/"), 
        13, 22, 0); 
      text.setSpan(new URLSpan("http://www.yahoo.com/"), 
        28, 36, 0); 
      text.setSpan(new URLSpan("http://www.pmstudy.com"), 41, 51, 0); 

      richTextView.setMovementMethod(LinkMovementMethod.getInstance()); 
      richTextView.setText(text, BufferType.SPANNABLE); 

      d.setContentView(v); 
      d.show(); 

     } 
    }); 

    } 

} 
Смежные вопросы