我正在尝试获取文本视图以链接到网站,但找不到android中xml的ID。任何帮助都会很棒。这是代码

它不会找到R.id.textviewlink

public class Fragment_2 extends Fragment{
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

        return inflater.inflate(R.layout.fragment_2, null);

        TextView t2 = (TextView) getView().findViewById(R.id.textviewlink);
        t2.setMovementMethod(LinkMovementMethod.getInstance());
    }
}


XML格式

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="10dip"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:background="@drawable/backgroundw">

<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

            <TextView
    android:id="@+id/textviewlink"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="Free PDF Download"
    android:linksClickable="true"/>

    </LinearLayout>
    </ScrollView>
    </RelativeLayout>

最佳答案

那是因为您在找到视图项之前已经返回了膨胀的布局。有两种选择。

首先,inflate()方法始终需要三个参数:

inflater.inflate(R.layout.file_name, container, false);


将以下内容放入onStart

TextView t2 = (TextView) getView().findViewById(R.id.textviewlink);
t2.setMovementMethod(LinkMovementMethod.getInstance());


或只是使用此:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
   View v = inflater.inflate(R.layout.fragment_2, container, false); //don't forget the third argument here
   TextView t2 = (TextView) v.findViewById(R.id.textviewlink);
   t2.setMovementMethod(LinkMovementMethod.getInstance());

   return v;
 }

07-28 00:01