Android中的setText和getText片段

时间:2015-03-18 18:06:07

标签: android fragment

当我点击ActionBar上的按钮时,当我尝试getText()editText应用程序崩溃时,我可以onCreate setTexteditText活动public class TransactionAdd extends FragmentActivity... EditText editText; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_transactions_pager); mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); editText = (EditText) mViewPager.findViewById(R.id.editText); ActionBar mActionBar = getActionBar(); mActionBar.setDisplayShowHomeEnabled(false); mActionBar.setDisplayShowTitleEnabled(false); LayoutInflater mInflater = LayoutInflater.from(this); View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null); ImageView imageView = (ImageView) mCustomView.findViewById(R.id.imageView); imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { editText.setText("TEST"); // ...when I test this one, it works } }); mActionBar.setCustomView(mCustomView); mActionBar.setDisplayShowCustomEnabled(true); editText.setText("TEST"); // ...this one does not 。问题是editText返回null。

编辑:

{{1}}

1 个答案:

答案 0 :(得分:1)

您需要在片段的OnCreateView方法中获取EditText的引用。

一个例子:

public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    yourEditTextVariable = (TextView) rootView.findViewById(R.id.yourId);
    return rootView;
    }
}