0

我有一个 FragmentActivity 和一个 Fragment,好吧,现在我想以编程方式将此 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);
}

}

这是片段活动:

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();

}

}

提前致谢!:)

4

0 回答 0