2017-04-08 18 views
-1

組片段的EditText我有一個包含兩個setter方法ProfileFragment類:從父Activty

public void setPseudo(String pseudo){ 
    textPseudo.setText(pseudo); 
} 
public void setEmail(String email){ 
    textEmail.setText(email); 
} 

而且在我的活動,我想調用這些函數:

user = new ProfileFragment(); 

if (intent != null) { 

    user.setPseudo(intent.getStringExtra(USER_PSEUDO)); 
    user.setEmail(intent.getStringExtra(USER_EMAIL)); 
} 

它說:「能不解決方法...「。
這是否意味着我不能這樣做呢?

回答

2

你確定你沒有Profile類制定者?不是Fragment


片段通常不使用setter,它們使用參數。

原因是:如果你調用setEmail,然後你叫新片段中的一些觀點setText,你會得到一個NullPointerException因爲TextView從未初始化

Fragment profileFragment = new ProfileFragment(); 
Bundle args = new Bundle(); 
if (intent != null) { 
    args.putAll(intent.getExtras()); 
} 
profileFragment.setArguments(args); 

// Show new Fragment 
getSupportFragmentManager() 
    .replace(R.id.content, profileFragment) 
    .commit(); 

而且裏面的片段的onCreateView,你可以現在在片段中的「onCreateView」的方法使用,例如

final Bundle args = getArguments(); 

String pseudo = ""; 
if (args != null) { 
    pseudo = args.getString(YourActivity.USER_PSEUDO); 
} 
textPseudo.setText(pseudo); 
+0

,USER_PSEUDO解決不了.. –

+0

右鍵,你需要靜態IMPO室溫它 –

+0

已經在範圍上,因爲我在一個又一個活動宣佈它 –