我在应用中创建功能时遇到问题。我想在我的应用程序的一个选项卡中的Button更新TextViews,它位于我的应用程序的另一个选项卡中。不幸的是我的解决方案不起作用 - 每次触摸Button1时都会抛出NPE。我的代码:
应更新的标签:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SummaryFragment extends Fragment {
TextView textViewOne;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View summary= inflater.inflate(R.layout.fragment_summary, container, false);
textViewOne = (TextView) summary.findViewById(R.id.books);
textViewOne.setText("You have read " + Stats.book + " books");
return summary;
}
public void updateStats() {
textViewOne.setText("You have read " + Stats.book + " books");
}
}
按钮所在的标签:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class ReadingStarted extends Fragment {
static FirstPageFragmentListener firstPageListener;
public SummaryFragment summaryFragment;
public ReadingStarted() {
}
public ReadingStarted(FirstPageFragmentListener listener) {
firstPageListener = listener;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View started = inflater.inflate(R.layout.fragment_started, container, false);
Button button1 = (Button) started.findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Stats.book=Stats.book+1;
summaryFragment.updateStats();
}
});
return started;
}
}
答案 0 :(得分:2)
代码中的问题:
请参阅有关Fragments的开发者文档。