//This is the TextViewExample class
public class TextViewExample {
private TextView mTextViewExample;
public TextViewExample(Activity activity) {
mActivity = activity;
mTextViewExample = (TextView)mActivity.findViewById(R.id.TextViewLayout);
}
}
//This is the Fragment class
public class TextViewFragment extends Fragment {
private TextViewExample mText;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mText = new TextViewExample(getActivity());
}
}
用户界面中未更新 mText
!有人可以通过调用片段中的活动来解释正确显示TextView
的方法吗?
谢谢=)
答案 0 :(得分:0)
您可以直接访问片段中的活动[<Fact>]
let fact () =
let rng = Random ()
let a = rng.Next() % 2 = 0
let b = rng.Next() % 2 = 0
a && b // <- breakpoint here works
()
(假设此片段已附加到活动中):
TextView
务必检查//This is the Fragment class
public class TextViewFragment extends Fragment {
private TextView mText;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// you need to inflate the xml file holding this TextView.
mText = (TextView) getActivity().findViewByid(R.id.<your-text-view-id>;
// do something with your TextView
}
}
以避免NPE。
答案 1 :(得分:0)
<强>活动:强>
public class MainActivity {
private TextView mTextViewExample;
protected void onCreate(Bundle savedInstanceState) {
...
mTextViewExample = (TextView) findViewById(R.id.TextViewLayout);
}
}
public void setTextViewExampleText(String text) {
mTextViewExample.setText(text);
}
<强> TextViewFragment 强>
public class TextViewFragment extends Fragment {
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
((MainActivity) getActivity()).setTextViewExampleText("text");
}
}