2014-07-19 5 views
0

안녕하세요, 안드로이드 어플리케이션에 Fragment을 사용하고 있습니다. 나는 내가 얻을 수있는 전망을 얻을 필요가있다.안드로이드에서 fragment의 뷰를 얻는 방법

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

mNoteEditText 내가 그들에게 정적 변수를 이유로 인해 Fragment 클래스는 정적 할 필요가 onBackPressed 그래서 모든보기 참조에 액세스해야합니다. 나는 정적 변수에 대한 모든 관점을 좋은 접근 방식이 아닌 것으로 알고있다. 어떻게하면 뷰의 정적 변수를 만들지 않아도 될까요?

사전에 도움을 주셔서 감사합니다.

답변

0

Fragment에는 getView()이라는 방법이 있습니다. 그것에 에 붙어있는 한 FragmentView를 얻을 수있다. 당신이 Fragment 내부 View를 찾고 있다면

View view = fragment.getView(); 

그러나 당신은 또한 단지 Activity에서 findViewById() 그것을 얻을 수 있습니다. 다시 작동하려면 FragmentActivity에 연결해야합니다.

but 그렇게해서는 안됩니다. 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 당신은이 작업을 수행 할 수 있습니다

public class NotesActivity extends Activity { 

    private int bookId; 
    private int chapterId; 

    private NoteFragment noteFragment; 

    @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) { 
      this.noteFragment = new NoteFragment(); 
      getFragmentManager().beginTransaction().add(R.id.container, this.noteFragment).commit(); 
     } 

     // Now you can interact with the Fragment 
     this.noteFragment.setText("some text"); 

     ... 

     if(!this.noteFragment.isEmpty()) { 
      String note = this.noteFragment.getText(); 
      ... 
     } 
    } 
} 
+0

당신이의 무엇을 의미하는지 확실하지 않다 "그것과 상호 작용하는 조각의 공용 메소드를 작성합니다." 제발 도와주세요 –

+0

예를 들어 보았습니다. –

관련 문제