TextView.setText在函数调用中不起作用。我在方法中传递数据(“changeText”)。代码不起作用。应用停止工作。当我尝试更改onActivityCreated中的文本时它可以工作,但是当我在函数中传递数据时它不起作用
public class Fragment_b extends Fragment {
TextView tv;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_b, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tv = (TextView) getActivity().findViewById(R.id.textView);
changeText(90);
}
public void changeText(int data)
{
tv = (TextView) getActivity().findViewById(R.id.textView);
tv.setText(String.valueOf(data));
}
}
答案 0 :(得分:1)
首先将mainView声明为全局。然后使用那个来查找你的视图,调用getActivty()。findViewById ...没有使用与你相同的布局。
private View rootView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_b, container, false);
return rootView;
}
然后
tv = (TextView) rootView.findViewById(R.id.textView);
答案 1 :(得分:0)
public class Fragment_b extends Fragment {
TextView tv;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_b, container, false);
tv = (TextView)v.findViewById(R.id.textView);
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
changeText(90,tv);
}
public void changeText(int data,TextView tv)
{
tv.setText(String.valueOf(data));
}
}
答案 2 :(得分:0)
getActivity().runOnUiThread(new Runnable()
{
@Override
public void run()
{
changeText(90);
}
});