我有一个FragmentActivity和Fragment,好吧,现在我想以编程方式将这个片段添加到Activity中,我还想更新一个TextView的值。但我一直得到NullPointException。 这里需要一些帮助...... :(
这是我的代码:
public class NewsDetailsFragment extends Fragment {
private View _currentview = null;
public View getCurrentView() {
return _currentview;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
_currentview = inflater.inflate(R.layout.newsdetails_layout, container,
false);
Button b = (Button) _currentview.findViewById(R.id.btnReplace);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
transaction.replace(R.id.landscapeLayout,
new ReplacementFragment(), "replace");
} else {
transaction.replace(R.id.newsdetailsPortrait,
new ReplacementFragment(), "replace");
}
transaction.addToBackStack(null);
transaction.commit();
}
});
return _currentview;
}
public void setNewsContent(String content) {
TextView lblNewsContent = (TextView) getView().findViewById(
R.id.lblNewsContent);
lblNewsContent.setText(content);
lblNewsContent.setTextColor(Color.CYAN);
}
}
这是FragmentActivity:
public class NewsDetailsActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsdetailsactivity_layout);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
// setContentView(R.layout.newsdetails_layout);
NewsDetailsFragment detailsFragment = new NewsDetailsFragment();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.add(R.id.newsdetailsPortrait, detailsFragment,
"newsdatails");
String newString = getIntent().getStringExtra("news");
if (null != newString) {
TextView t = (TextView) detailsFragment.getView().findViewById(
R.id.lblNewsContent);
t.setText(newString);
t.setTextColor(Color.GREEN);
}
transaction.commit();
}
}
提前致谢! :)