Я просто начинаю разработку Android, и недавно я начал учебник по Android на developer.android.com. До сих пор все казалось прекрасным. Я делаю этот курс http://developer.android.com/training/basics/fragments/communicating.html, и я застрял. Я немного изменил его, потому что мне нужна была большая гибкость, поэтому я добавляю свой фрагмент во время выполнения. Я потратил как час на поиск ответа, но не смог найти решение для моей проблемы. :(FindFragmentByTag возвращает значение null.
Вот моя проблема: Я хочу общаться с моим фрагментом так же, как в учебнике, но я использую findFragmentByTag, вместо findFragmentById я сделал все, что мог найти в Интернете, но он говорит:.
java.lang.RuntimeException: не удается запустить Activity 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");
}
}
И Fragment:
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