gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:27:39 25 4
gpt4 key购买 nike

我是 fragment 的新手,我正在开发一个使用带有选项卡的滑动 View 的应用程序。我的目标是获取存储在字符串数组中的 TextView 显示文本,并在应用程序重新启动时更改。但是当我使用 findViewById 时似乎出现了问题。

代码:

首先.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]);


}

}

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>

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

最佳答案

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]);
}
}

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

关于Android-findViewById(int)方法未定义类型优先(Fragment),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20981487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com