我正在尝试使用这种简单的方法来更改片段文本视图,但是每次尝试使用该片段代码打开片段的活动时,应用程序都会崩溃
public class FragmentContrat extends Fragment {
public FragmentContrat() {}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.contrat_fragment, container, false);
update();
return view;
}
public void update() {
TextView textView = (TextView)getView().findViewById(R.id.souscripteur_txt);
textView.setText("milan");
}
但是,当我将相同的代码放在onCreateView中时,它可以正常工作并且TextView会发生变化:
public class FragmentContrat extends Fragment {
public FragmentContrat() {}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.contrat_fragment, container, false);
TextView textView = (TextView)view.findViewById(R.id.souscripteur_txt);
textView.setText("milan");
return view;
}
活动代码:
public class DetailsContrat extends AppCompatActivity {
TabLayout details_tab;
AppBarLayout details_bar;
ViewPager details_pager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_contrat);
Intent i = getIntent();
String client_id = i.getStringExtra("client_id");
details_tab=(TabLayout)findViewById(R.id.details_tab);
details_bar=(AppBarLayout) findViewById(R.id.details_bar);
details_pager=(ViewPager)findViewById(R.id.details_pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
FragmentContrat fragmentContrat = new FragmentContrat();
FragmentVehicule fragmentVehicule = new FragmentVehicule();
FragmentGaranties fragmentGaranties = new FragmentGaranties();
adapter.AddFragment(fragmentContrat,"MON CONTRAT");
adapter.AddFragment(fragmentVehicule,"MA VOITURE");
adapter.AddFragment(fragmentGaranties,"MES GARANTIES");
details_pager.setAdapter(adapter);
details_tab.setupWithViewPager(details_pager);
}
}
答案 0 :(得分:0)
我认为您需要在更新方法中传递您的观点
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.contrat_fragment, container, false);
update(view);
return view;
}
public void update(View view) {
TextView textView = (TextView)view.findViewById(R.id.souscripteur_txt);
textView.setText("milan");
}
答案 1 :(得分:0)
您正在onCreateView
中创建片段的视图。因此,如果调用getView()
,则要获取片段视图,您将获得null,因为您尚未返回刚刚创建的视图。
您可以:
onCreateView
中设置文本,而在onViewCreated(View view, Bundle savedInstanceState)
中设置文本,在创建视图(docs)后调用该文本