Android-方法findViewById(int)未定义类型优先(Fragment)

Ant*_*ksh 1 xml random android textview android-fragments

我是片段新手,我正在使用带选项卡的滑动视图开发应用程序.我的目标是获得存储在字符串数组中的textview显示文本,并在应用程序重新启动时进行更改.但是当我使用findViewById时似乎有问题.

码:

First.java

import java.util.Random;

import android.support.v4.app.Fragment;
import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class first extends Fragment{

String[] strArr;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View rootView = inflater.inflate(R.layout.first_xml, container, false);
    strArr = getResources().getStringArray(R.array.quote);
             //quote is the name given to the string array

    return rootView;
}




@Override
public void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    refreshTV();
}

void refreshTV(){
        TextView tv = (TextView)findViewById(R.id.text1);
        Random ran = new Random();
        int c = ran.nextInt(strArr.length);
        tv.setText(strArr[c]);


    }

}
Run Code Online (Sandbox Code Playgroud)

2.first_xml.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#fa6a6a" >

<TextView android:layout_width="fill_parent"
    android:id="@+id/text1"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="@array/quote"
    android:textSize="40dp"
    android:layout_centerInParent="true"/>


</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.如果我提到的任何内容不够明确,请告诉我.谢谢 !

Yja*_*jay 5

Fragment课程没有该findViewById(...)方法,因此您必须从您rootView或您的方式获取您的观点Activity.我建议你成为你TextView的成员,Fragment从你的网站上检索它rootView,并根据需要引用它.

public class first extends Fragment {

String[] strArr;
TextView tv;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View rootView = inflater.inflate(R.layout.first_xml, container, false);
    tv = rootView.findViewById(R.id.text1);
    strArr = getResources().getStringArray(R.array.quote);
             //quote is the name given to the string array

    return rootView;
}

@Override
public void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    refreshTV();
}

void refreshTV(){
        Random ran = new Random();
        int c = ran.nextInt(strArr.length);
        tv.setText(strArr[c]);
    }
}
Run Code Online (Sandbox Code Playgroud)

(已编辑删除对findViewById的冗余调用.)