我的測試項目有一個主要活動如下:安卓:從片段中處理用戶輸入
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.display_message, menu);
return true;
}
public void sendMessage(View view){
FragmentManager frManager = getFragmentManager();
FragmentTransaction transaction = frManager.beginTransaction();
Frag fr= new Frag();
transaction.add(R.id.stuuf, fr);
transaction.addToBackStack(null);
transaction.commit();
}
}
而且主要有以下佈局:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/stuuf"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingTop="?android:attr/actionBarSize" >
<Button android:id="@+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"/>
</TableLayout>
當用戶點擊該按鈕以下片段顯示包含第二個按鈕:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Frag" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="180dp"
android:onClick="buttonClicked"
android:text="Button" />
</RelativeLayout>
而這個類應該是控制它:
public class Frag extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.frag_test, null);
}
public void buttonClicked(){
System.out.println("Hello!");
}
}
現在,有,當我點擊第二個按鈕,系統進入尋找在MainActivity而不是在破片的buttonClicked()方法的問題,由此給我下面的錯誤:
java.lang.IllegalStateExcetion: Could not find method buttonClicked(View) in the activity class com.spacitron.mytestproject.MainActivity for onClick handler on view class android.widget.Button with id 'button1'
很顯然,我應該能夠處理從片段類本身,所以我必須做一些完全錯誤的片段會發生什麼,我只是不能找出什麼。