[英]How can activity call a method inside fragment created dynamically
我有一個主要活動,該活動使用以下代碼創建片段
private void launchFragment(int pos)
{
Fragment f = null;
String title = null;
if (pos == 1)
{
title = "Friends";
f = new FriendList();
}
else if (pos == 2)
{
title = "Notes";
f = new NoteList();
}
else if (pos == 3)
{
title = "Projects";
f = new ProjectList();
}
else if (pos == 5)
{
title = "About";
f = new AboutUs();
}
else if (pos == 6)
{
startActivity(new Intent(this, Login.class));
finish();
}
if (f != null)
{
while (getSupportFragmentManager().getBackStackEntryCount() > 0)
{
getSupportFragmentManager().popBackStackImmediate();
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, f).addToBackStack(title)
.commit();
}
}
這是片段的代碼。
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.group_chat, null);
loadConversationList();
contactName = this.getArguments().getString("contactusername");
contactId = this.getArguments().getString("contactid");
ListView list = (ListView) v.findViewById(R.id.list);
adp = new ChatAdapter();
list.setAdapter(adp);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
list.setStackFromBottom(true);
txt = (EditText) v.findViewById(R.id.txt);
txt.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_FLAG_MULTI_LINE);
setTouchNClick(v.findViewById(R.id.btnCamera));
setTouchNClick(v.findViewById(R.id.btnSend));
return v;
}
我想在上面的片段類中調用一個方法。 我無法執行此操作,因為我沒有在XML文件中提供該片段的ID。 我沒有使用XML加載靜態片段。 因此,我沒有ID。
我已經看到了這個和這個在StackOverflow的問題,但他們沒有解決我的問題。
如果有人知道如何解決這種情況,請提供幫助。
首先,使您的所有片段都實現一個接口。 該接口將返回一個字符串(例如),該字符串將標識您的片段,然后使用findFragmentById()
獲取片段后,將片段findFragmentById()
為它,如下所示:
創建你的界面
public interface IFragmentName
{
public String getFragmentName();
}
實現您的界面(例如,在NoteList
)
public NoteList extends Fragment implements IFragmentName
{
//Do your stuff...
public String getFragmentName()
{
return "NoteList";
}
}
之后,從活動中獲取當前片段
IFragmentName myFragment = (IFragmentName) getSupportFragmentManager().findFragmentById(R.id.content_frame);
最后檢查您的getFragmentName()
值並將其getFragmentName()
為所需的片段:
if(myFragment.getFragmentName().equals("NoteList")
{
NoteList myNoteListFragment = (NoteList) myFragment;
myNoteListFragment.callMyMethod(); //here you call the method of your current Fragment.
}
我已經在沒有任何IDE的情況下對這些代碼片段進行了編碼,所以也許我錯過了分號或類似內容:)
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.