gpt4 book ai didi

android - Android 中的 fragment - 无法动态编辑 TextView

转载 作者:行者123 更新时间:2023-11-29 21:36:36 24 4
gpt4 key购买 nike

当我尝试使用时出现错误:TextView tv = (TextView) getView().findViewById(R.id.textView1);在我的 FragmentOne 类中。

我是 fragment 的新手,我希望学习 PagerView,但我不知道如何动态更改我的小部件。

MainActivity.java

public class MainActivity extends FragmentActivity {
FragmentOne mFrag;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if(savedInstanceState==null){
mFrag = new FragmentOne();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragment_layout, mFrag).commit();
}

}
}

layout/activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/fragment_layout">

<FrameLayout
android:id="@+id/fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />


</LinearLayout>

FragmentOne.java

public class FragmentOne extends Fragment {
TextView tv;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment, container, false);
// Inflate the layout for this fragment
tv = (TextView) getView().findViewById(R.id.textView1);
tv.setText("Yellow World!");
return v;
}
}

layout/fragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Blellow World!" />

</LinearLayout>

日志文件:https://www.dropbox.com/home/Projects?select=log.txt错误是“无法开始 Activity ”如果我删除

,错误就会消失
tv = (TextView) getView().findViewById(R.id.textView1);
tv.setText("Yellow World!");

来自 FragmentOne 类的行。

我今天只学习了 fragment ,如果它很简单,我很抱歉!

最佳答案

您应该使用膨胀 View 而不是 getView()。

 tv = (TextView) v.findViewById(R.id.textView1);

关于android - Android 中的 fragment - 无法动态编辑 TextView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18303408/

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