如何从片段TextView打开URL? [英] How to open URL from Fragment TextView?
问题描述
我有一个带有多个选项卡的活动,每个选项卡都包含一个片段,其中包含一些文本.我想要一个带有阅读更多"的文本,它是指向URL的链接.没有链接,一切正常,但是当我尝试实现它时,我得到
I have an activity with multiple tabs and each tab consists of a fragment with some text inside. I would like to have a text with "Read More" which is a link to an URL. Without having the link, everything works fine, but when I try to implement it, I get
E/UncaughtException:java.lang.NullPointerException
E/UncaughtException: java.lang.NullPointerException
所以我认为这是实现它的方式.现在,该片段具有以下内容:
So I assume it is the way I implement it. Right now, the fragment has this:
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具有以下功能:
"read_more" layout has this for the 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:
And link_to_website is given in the strings:
< string name = "link_to_the_website" > < a href = "www.google.com/" > Read More Here < /a></string >
有人可以帮我弄清楚我写错了什么吗?
Can anyone help me to figure out what is it that I wrote wrong?
推荐答案
将膨胀视图用作
TextView t2 = (TextView) rootView.findViewById(R.id.read_more);
或覆盖onViewCreated
,然后您可以使用getView()
或定向传递的视图
or override onViewCreated
and then you can use getView()
or directed passed view
@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 ,因此出现问题
Because getview
will only return the actual view which was previously created and returned by onCreateView
otherwise it will return null, hence the issue