我有一个片段
public class Player extends Fragment {
private TextView songTitleLabel,songNameSinger;
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
view = inflater.inflate(R.layout.player, container, false);
// All player buttons
songTitleLabel = view.findViewById(R.id.Title);
songNameSinger = view.findViewById(R.id.singer);
return view;
}
在同一片段中有一个方法可以做到这一点
public void playSong(String id ,String Singer) {
songTitleLabel.setText(id);
songNameSinger.setText(Singer);
}
我在主要活动中将此方法称为
String name = CardList.get(position).getId();
String singer = CardList.get(position).getSinger();
Player player = new Player();
player.playSong(name,singer);
并且我确保当字符串转到Fragment方法时它不会变成null
,所以我放了一个Log并看到了它的not null
,但是当我制作TextView.setText
时它附带了这个错误
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
所以我尝试另一件事,我像这样由我自己设置值
songTitleLabel.setText("Value");
它确实起作用了,我不知道问题出在哪里... 谢谢大家...
答案 0 :(得分:1)
仅创建该fragment
的对象不会调用oncreateview of that fragment
(您在其中初始化视图),因此您的TextView
为 null
请像下面的示例一样从Activity调用您的片段方法
FragmentManager fm = getSupportFragmentManager();
Player fragment = (Player )fm.findFragmentById(R.id.fragment_id);
fragment.playSong(name,singer);
OR
Player fragment = (Player ) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.playSong(name,singer);