我只是一個在android開發中的begginer,最近我已經在developer.android.com上啓動了Android教程。一切似乎都很好,直到現在。我正在做這個課程http://developer.android.com/training/basics/fragments/communicating.html exacly,我卡住了。我改變了一下,因爲我想要更多的靈活性,所以我添加了我的片段運行時。我花了一個小時尋找答案,但無法找到解決我的問題的任何解決方案。 :(FindFragmentByTag返回null。
這裏是我的問題: 我想就像在教程,我的片段進行溝通,但我用findFragmentByTag,而不是findFragmentById我所做的一切,我能找到在互聯網上,但它說:
java.lang.RuntimeException:無法啓動活動ComponentInfo {com.example.filip.t1/com.example.filip.t1.MainActivity}:java.lang.NullPointerException:嘗試調用虛擬方法'void android。 Widget.TextView.setText(java.lang.CharSequence)'對空引用
這是我的MainActivity:
public class MainActivity extends FragmentActivity
implements TextFragment.OnHeadlineSelectedListener{
EditText editText;
TextFragment fragment = new TextFragment();
Context context = this;
String fragment_tag = "FRAGMENTO";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction().add(R.id.frameLayout, fragment, fragment_tag).commit();
getSupportFragmentManager().executePendingTransactions();
onArticleSelected(1);
}
@Override
public void onArticleSelected(int position) {
TextFragment textFragment = (TextFragment) getSupportFragmentManager().findFragmentByTag(fragment_tag);
if(textFragment != null){
String strung = "It should be displayed, but it is not... :(";
textFragment.updateText(strung);
}else{
Log.e("tag_prog","textFragment == null");
}
}
和碎片:
public class TextFragment extends Fragment {
TextView textView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_text, container, false);
textView = (TextView)rootView.findViewById(R.id.textView);
return rootView;
}
OnHeadlineSelectedListener mCallBack;
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
@Override
public void onResume(){
super.onResume();
}
public void onAttach(Activity activity){
super.onAttach(activity);
try{
mCallBack = (OnHeadlineSelectedListener) activity;
} catch(ClassCastException e) {
throw new ClassCastException(activity.toString() + "must implement OHSL");
}
}
public void funkcja(){
}
public void updateText(String s) {
textView.setText(s);
}
感謝任何
在你的'TextFragment.onCreateView'你不應該回到你的'textView'? – aribeiro
我應該嗎?我真的不知道。但爲什麼 ? – buRn
不,你不應該。 – barq