[英]GetText from Fragment returns null but setText works
在我的MainActivity
我調用一個 Fragment 並在其活動時將布爾mFragment
設置為 true。 現在我在 Fragment 中聲明的TextViews
設置了一些 Text 並且它工作正常。 但是,當 Fragment 中聲明的Button
調用MainActivity
的方法時,突然mFragment
為 false,我無法使用TextViews
getText
,因為它們為空。 我不知道為什么會這樣。
主要活動
public class MainActivity extends AppCompatActivity implements SensorEventListener {
MainFragment mainFragment;
HistoryActivity historyFragment;
boolean mFragment = false;
//....
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainFragment = new MainFragment();
historyFragment = new HistoryActivity();
if(!mFragment) {
getMainFragment();
}
//...SenserManager and so on
@Override
public void onSensorChanged(SensorEvent event){
if (mFragment) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
DecimalFormat df = new DecimalFormat("0.000");
//This works constantly:
mainFragment.textViewX.setText("X = " + df.format(x));
mainFragment.textViewY.setText("Y = " + df.format(y));
mainFragment.textViewZ.setText("Z = " + df.format(z));
}
}
public void writeEntry(){ //called in Fragment
if(mFragment) {
//This doesn't work (isn't even called because mFragment is false)
String x = (String) mainFragment.textViewX.getText();
String y = (String) mainFragment.textViewY.getText();
String z = (String) mainFragment.textViewZ.getText();
}
}
public void getMainFragment() {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, mainFragment);
transaction.addToBackStack(null);
transaction.commit();
mFragment = true;
}
分段
public class MainFragment extends Fragment {
TextView textViewX;
TextView textViewY;
TextView textViewZ;
Button button;
MainActivity mainActivity = new MainActivity();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
textViewX = (TextView) view.findViewById(R.id.textViewX);
textViewY = (TextView) view.findViewById(R.id.textViewY);
textViewZ = (TextView) view.findViewById(R.id.textViewZ);
button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mainActivity.writeEntry();
}});
return view;
}
}
使用回調接口從片段交互到活動。 請參考。 這是一個非常推薦的方法。 http://developer.android.com/training/basics/fragments/communicating.html#Implement
你的溝通和幾點是錯誤的。
使用以下用法,您可能想訪問當前MainAcitivity 的方法或字段。 但這不是 MainAcitivity 的當前實例。 您剛剛實例化了一個新的(也沒有活動的生命周期)
MainActivity mainActivity = new MainActivity();
所以這就是為什么 mFragment boolen 變量是假的,而其他項目也是空的,比如 textviews。
你可以參考以下鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.