在TextView中还可以实现单击文字,来跳转到设定的Activity中去,是不是很神奇呀,
先看看实现的效果:
MainActivity界面截图:
单击"显示Activity1"之后,弹出Activity1的窗口,截图如下:
同样,单击"显示Activity2"弹出界面截图:
实现代码如下:
由于main.xml文件比较简单,这里就不给出源代码了哦,
MainActivity.java
public class Android_TextviewActivity extends Activity { private TextView textView1; private TextView textView2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /* * TextView中实现Activity的跳转 * */ textView1=(TextView)findViewById(R.id.textview1); textView2=(TextView)findViewById(R.id.textview2); String text1="显示Activity1"; String text2="显示Activity2"; SpannableString spannableString1=new SpannableString(text1); spannableString1.setSpan(new ClickableSpan() { @Override public void onClick(View view) { Intent intent=new Intent(Android_TextviewActivity.this,Activity1.class); startActivity(intent); } }, 0, text1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); SpannableString spannableString2=new SpannableString(text2); spannableString2.setSpan(new ClickableSpan() { @Override public void onClick(View view) { Intent intent=new Intent(Android_TextviewActivity.this,Activity2.class); startActivity(intent); } }, 0, text2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView1.setText(spannableString1); textView1.setMovementMethod(LinkMovementMethod.getInstance()); textView2.setText(spannableString2); textView2.setMovementMethod(LinkMovementMethod.getInstance()); } }
Activity1.java
package com.android.mytextview; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class Activity1 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("Activity1"); TextView textView = new TextView(Activity1.this); textView.setText("这里是Activity1的地盘"); setContentView(textView); } }
Activity2.java
package com.android.mytextview; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class Activity2 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("Activity2"); TextView textView = new TextView(Activity2.this); textView.setText("这里是Activity2的地盘"); setContentView(textView); } }