我有一个带有多个选项卡的活动,每个选项卡都由一个片段组成,里面有一些文本。我想要一个带有“阅读更多”的文本,它是指向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;
  }
}





TextView的“ read_more”布局具有以下功能:



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





谁能帮我弄清楚我写错了什么?

最佳答案

以太将您的膨胀视图用作

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 >"));

关于android - 如何从 fragment TextView打开URL?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48264229/

10-12 06:31