如何从Fragment TextView中打开URL?

时间:2018-01-15 13:43:41

标签: android android-fragments url hyperlink

我有一个包含多个标签的活动,每个标签都包含一个片段,里面有一些文字。我想要一个带有“Read More”的文本,这是一个URL的链接。没有链接,一切正常,但当我尝试实现它时,我得到了

  

E / UncaughtException:java.lang.NullPointerException

所以我认为这是我实现它的方式。现在,片段有这个:

public class About_us extends Fragment {

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_about_us, container, false);
    //The part below is For Read More
    TextView t2 = (TextView) getView().findViewById(R.id.read_more);
    if (t2 != null) {
      t2.setMovementMethod(LinkMovementMethod.getInstance());
    }

    return rootView;
  }
}

“read_more”布局为TextView提供了这个:

< TextView
android: id = "@+id/read_more"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: clickable = "true"
android: text = "@string/link_to_the_website"
android: textColor = "@color/buttonColorPressed" / >

link_to_website在字符串中给出:

< string name = "link_to_the_website" > < a href = "www.google.com/" > Read More Here < /a></string >

任何人都可以帮我弄清楚我写错了什么吗?

3 个答案:

答案 0 :(得分:2)

Ether将您的虚增视图用作

TextView t2 = (TextView) rootView.findViewById(R.id.read_more); 

或覆盖onViewCreated,然后您可以使用getView()或定向传递的视图

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    TextView t2 = (TextView) view.findViewById(R.id.read_more);
    // or TextView t2 = (TextView) getView().findViewById(R.id.read_more);
}

因为 getview只会返回onCreateView 之前创建并返回的实际视图,否则会返回null ,因此问题

getView()

  

Get the root view表示片段的布局(one returned by onCreateView(LayoutInflater, ViewGroup, Bundle)),如果提供的话。

因此您无法在getView完成之前使用onCreateView。 然后使用这种方法,您将任务分成两部分

onCreateView:用于查看通货膨胀

onViewCreated:用于视图和侦听器初始化

更新:添加链接

t2.setMovementMethod(LinkMovementMethod.getInstance());
t2.setText(Html.fromHtml("< string name = 'link_to_the_website' > < a href = 'https://www.google.com/' > Read More Here < /a></string >"));

答案 1 :(得分:1)

尝试更改代码中的行

TextView t2 = (TextView) rootView.findViewById(R.id.read_more);

并在textview中添加xml中的属性

android:autoLink="web" 

答案 2 :(得分:0)

// declare interface in fragment   
 public interface OnTextSelectedListener
  {
   void ontextSelected(String url);
  }

  @Override
  public void onAttach(Activity activity) {
      super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mCallback = (OnTextSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnTextSelectedListener");
    }
}

// Implement interface in activity


   public void ontextSelected(String   url) {
  // load your webview
   }

检查此link以更好地理解片段通信。