[英]How to send data from fragment to fragment within same fragment activity?
[英]How to properly use an Activity with a Fragment within?
我試圖獲得一個可以與Fragment
一起使用的Activity
(稍后我將與更多片段一起使用)。 我為此類Fragment
創建了一個類和一個布局,並將它們包括在Activity
的布局中。
這是我的Activity
類的樣子:
public class Expressa extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
這是我的Fragment
類的樣子:
public class MessageFragment extends Fragment {
EditText messageField;
private onNewMessageListener listener;
public View OnCreateVie(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.message_fragment_layout,container,false);
messageField = (EditText) view.findViewById(R.id.messageField);
return view;
}
public void doTextToSpeech(View view) {
String text = messageField.getText().toString().trim();
new TextToSpeechServices().execute(text);
}
public interface onNewMessageListener {
public void newMessage(String msg);
}
}
Activity
布局:
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:orientation="vertical" >
<fragment
android:id="@+id/messageFragment"
class="apps.android.expressa.expressa.MessageFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="@layout/message_fragment_layout" />
</LinearLayout>
片段的:
但是我總是收到一個IllegalStateException
抱怨MessageFragment
沒有創建視圖。
這是片段的布局 ,這是完整的stacktrace 。 我正在使用編譯SDK API 22,構建工具版本21.1.2,最小SDK是16。我怎么了?
IllegalStateException
是因為Android在MessageFragment
中未檢測到onCreateView()
的實現。 您拼寫了onCreateView()
方法的名稱不正確。
更換
public View OnCreateVie(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
同
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
使用正確的方法簽名和@Override
批注,框架將正確解釋您已為Fragment
指定一個View
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.