如何在Android中获取片段视图

时间:2014-07-19 18:08:55

标签: android android-fragments

您好我在我的Android应用程序中使用Fragment。我需要获得我可以使用的视图。

mNoteEditText = rootView.findViewById(R.id.noteEditText);

mNoteEditText需要访问此onBackPressed,因此我需要将每个视图引用设为静态变量,因为Fragment类是静态的。我知道要使每个视图对静态变量都不是好方法。我怎么能这样做,我不需要制作视图的任何静态变量。

public class NotesActivity extends Activity {

    private int bookId;
    private int chapterId;

    private static EditText mNoteEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);

        // get data from intent that sent from home activity
        bookId = getIntent().getIntExtra("book_id", -1);
        chapterId = getIntent().getIntExtra("book_id", -1);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new NoteFragment()).commit();
        }
    }

    /**
     * A note fragment containing a note layout.
     */
    public static class NoteFragment extends Fragment {

        public NoteFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_notes,
                    container, false);
            mNoteEditText = (EditText) rootView.findViewById(R.id.noteEditText);
            return rootView;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        // get database instance
        MySQLiteOpenHelper db = MySQLiteOpenHelper.getInstance(this);

        Notes note = new Notes();
        note.setBookId(bookId);
        note.setChapterId(chapterId);
        note.setNote(mNoteEditText.getText().toString());

    }

}

请提前帮助和谢谢。

1 个答案:

答案 0 :(得分:0)

Fragment有一个名为getView()的方法。有了它,只要它附加到View,您就可以获得Fragment的{​​{1}}。

Activity

但如果您在View view = fragment.getView(); 内寻找View,您也可以从Fragment获取findViewById()。同样,Activity必须附加到Fragment才能生效。

但是你不应该这样做。 Activity之外的任何内容都不应与Fragment内的内容有任何关系。在Fragment中编写公共方法以与之交互。尝试这样的事情:

Fragment

现在在public static class NoteFragment extends Fragment { private EditText noteEditText; public NoteFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_notes, container, false); this.noteEditText = (EditText) rootView.findViewById(R.id.noteEditText); return rootView; } // I added the following 3 methods to interact with the Fragment public boolean isEmpty() { final String text = this.noteEditText.getText().toString(); return text.isEmpty(); } public String getText() { return this.noteEditText.getText().toString(); } public void setText(String text) { this.noteEditText.setText(text); } } 你可以这样做:

Activity