2015-02-14 3 views
0

Итак, у меня есть 3 вкладки ActionBar, которые запускают 3 разных класса фрагментов. В Tab1 actionBar у меня есть простая форма, которую пользователь заполняет, а данные затем сохраняются в базе данных SQLite, эта форма и выполняемые на ней задачи отлично работают как проект, но когда я пытался интегрировать его как фрагмент (FragmentTab1), то приложение падает, когда я нажимаю кнопку сохранения. Любые идеи относительно того, почему это может быть сбой? Я думаю, мне, возможно, придется реализовать onClickListener, может быть, не уверен, хотя! Я знаю, что способ, которым я использую вкладки и фрагменты, немного устарел, но я все равно хочу, чтобы он работал таким образом.Android-фрагменты в действииBar tabs

Error Log

 02-14 16:42:14.560 10914-10914/com.androidbegin.absfragtabhost/AndroidRuntime﹕ FATAL EXCEPTION: main 
Process: com.androidbegin.absfragtabhost, PID: 10914 
java.lang.IllegalStateException: Could not find a method addButtonClicked(View) in the activity class com.androidbegin.absfragtabhost.MainActivity for onClick handler on view class android.widget.Button with id 'addButtonClicked' 
     at android.view.View$1.onClick(View.java:3828) 
     at android.view.View.performClick(View.java:4456) 
     at android.view.View$PerformClick.run(View.java:18465) 
     at android.os.Handler.handleCallback(Handler.java:733) 
     at android.os.Handler.dispatchMessage(Handler.java:95) 
     at android.os.Looper.loop(Looper.java:136) 
     at android.app.ActivityThread.main(ActivityThread.java:5086) 
     at java.lang.reflect.Method.invokeNative(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:515) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
     at dalvik.system.NativeStart.main(Native Method) 
    Caused by: java.lang.NoSuchMethodException: addButtonClicked [class android.view.View] 
     at java.lang.Class.getConstructorOrMethod(Class.java:472) 
     at java.lang.Class.getMethod(Class.java:857) 
     at android.view.View$1.onClick(View.java:3821) 
     at android.view.View.performClick(View.java:4456) 
     at android.view.View$PerformClick.run(View.java:18465) 
     at android.os.Handler.handleCallback(Handler.java:733) 
     at android.os.Handler.dispatchMessage(Handler.java:95) 
     at android.os.Looper.loop(Looper.java:136) 
     at android.app.ActivityThread.main(ActivityThread.java:5086) 
     at java.lang.reflect.Method.invokeNative(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:515) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
     at dalvik.system.NativeStart.main(Native Method) 

FragmentTab1.java

package com.androidbegin.absfragtabhost; 

import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.app.Fragment; 
import android.content.Context; 
import android.content.Intent; 
import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.view.View.OnClickListener; 



public class FragmentTab1 extends Fragment { 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment1, container, false); 
    return rootView; 
} 

public class Activity extends ActionBarActivity { 

    TextView firstName; 
    EditText editTextName; 

    TextView textView5; 
    EditText editTextSurname; 

    TextView textView4; 
    EditText editTextMobile; 

    TextView textView2; 
    EditText editTextEmail; 

    TextView textView3; 
    EditText editTextAddress1; 

    TextView textView6; 
    EditText editTextAddress2; 

    MyDBHandler dbHandler; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     firstName = (TextView) findViewById(R.id.firstName); 
     editTextName = (EditText) findViewById(R.id.editTextName); 
     textView5 = (TextView) findViewById(R.id.textView5); 
     editTextSurname = (EditText) findViewById(R.id.editTextSurname); 
     textView4 = (TextView) findViewById(R.id.textView4); 
     editTextMobile = (EditText) findViewById(R.id.editTextMobile); 
     textView2 = (TextView) findViewById(R.id.textView2); 
     editTextEmail = (EditText) findViewById(R.id.editTextEmail); 
     textView3 = (TextView) findViewById(R.id.textView3); 
     editTextAddress1 = (EditText) findViewById(R.id.editTextAddress1); 
     textView6 = (TextView) findViewById(R.id.textView6); 
     editTextAddress2 = (EditText) findViewById(R.id.editTextAddress2); 

     dbHandler = new MyDBHandler(this, null, null, 1); 
     //printDatabase(); 
    } 


    //Add details to the database 
    public void addButtonClicked(View view) { 
     Details details = new Details(""); 
     details.setFirstname(editTextName.getText().toString()); 
     details.setSurname(editTextSurname.getText().toString()); 
     details.setPhone(editTextMobile.getText().toString()); 
     details.setEmail(editTextEmail.getText().toString()); 
     details.setAddress1(editTextAddress1.getText().toString()); 
     details.setAddress2(editTextAddress2.getText().toString()); 
     dbHandler.addDetails(details); 
     //printDatabase(); 
    } 
} 
} 

Fragment1.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/scrollView1" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
tools:context=".MainActivity" > 

<RelativeLayout 
    android:layout_width="match_parent" 
    android:layout_height="600dp" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:theme="@style/AppTheme" 
    android:touchscreenBlocksFocus="false"> 


    <!-- First name --> 

    <TextView 
     android:id="@+id/firstName" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignBottom="@+id/editTextName" 
     android:layout_alignParentStart="true" 
     android:layout_alignParentLeft="true" 
     android:text="@string/firstname" 
     android:textAppearance="?android:attr/textAppearanceMedium" /> 

    <EditText 
     android:id="@+id/editTextName" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:layout_marginTop="5dp" 
     android:layout_marginStart="82dp" 
     android:layout_marginLeft="90dp" 
     android:ems="10" 
     android:paddingTop="25dp" 
     android:inputType="text" > 
    </EditText> 



    <!-- Surname --> 

    <TextView 
     android:id="@+id/textView6" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/address2" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:layout_marginTop="33dp" 
     android:layout_below="@+id/editTextAddress1" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" /> 

    <EditText 
     android:id="@+id/editTextAddress2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:ems="10" 
     android:inputType="text" 
     android:layout_alignTop="@+id/textView6" 
     android:layout_alignLeft="@+id/editTextAddress1" 
     android:layout_alignStart="@+id/editTextAddress1" /> 




    <!-- Mobile Number --> 

    <TextView 
     android:id="@+id/textView5" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignBottom="@+id/editTextSurname" 
     android:layout_alignLeft="@+id/firstName" 
     android:layout_alignStart="@+id/firstName" 
     android:text="@string/surname" 
     android:textAppearance="?android:attr/textAppearanceMedium" /> 

    <EditText 
     android:id="@+id/editTextSurname" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignLeft="@+id/editTextMobile" 
     android:layout_alignStart="@+id/editTextMobile" 
     android:layout_below="@+id/editTextName" 
     android:layout_marginTop="22dp" 
     android:ems="10" 
     android:inputType="text" /> 





    <!-- Email Address --> 


    <TextView 
     android:id="@+id/textView2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignBottom="@+id/editTextEmail" 
     android:layout_alignLeft="@+id/firstName" 
     android:layout_alignStart="@+id/firstName" 
     android:text="@string/email" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:inputType="textEmailAddress" /> 

    <EditText 
     android:id="@+id/editTextEmail" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignStart="@+id/editTextMobile" 
     android:layout_alignLeft="@+id/editTextMobile" 
     android:layout_below="@+id/editTextMobile" 
     android:layout_marginTop="22dp" 
     android:ems="10" 
     android:inputType="textEmailAddress" /> 



    <!-- Address 1 --> 

    <TextView 
     android:id="@+id/textView3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignBaseline="@+id/editTextAddress1" 
     android:layout_alignBottom="@+id/editTextAddress1" 
     android:layout_alignParentLeft="true" 
     android:layout_toLeftOf="@+id/editTextEmail" 
     android:text="@string/address1" 
     android:textAppearance="?android:attr/textAppearanceMedium" /> 

    <EditText 
     android:id="@+id/editTextAddress1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignRight="@+id/editTextName" 
     android:layout_alignEnd="@+id/editTextName" 
     android:layout_below="@+id/editTextEmail" 
     android:layout_marginTop="30dp" 
     android:ems="10" 
     android:inputType="text" /> 




    <!-- Address 2 --> 

    <TextView 
     android:id="@+id/textView4" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_above="@+id/editTextEmail" 
     android:layout_alignLeft="@+id/textView5" 
     android:layout_alignStart="@+id/textView5" 
     android:text="@string/phone" 
     android:textAppearance="?android:attr/textAppearanceMedium" /> 


    <EditText 
     android:id="@+id/editTextMobile" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignLeft="@+id/editTextName" 
     android:layout_alignStart="@+id/editTextName" 
     android:layout_below="@+id/editTextSurname" 
     android:layout_marginTop="22dp" 
     android:ems="10" 
     android:inputType="phone"> 
    </EditText> 




    <Button 
     android:id="@+id/addButtonClicked" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:onClick="addButtonClicked" 
     android:text="@string/save" 
     android:layout_alignParentBottom="true" 
     android:layout_centerHorizontal="true" /> 


    <!-- <Button 
     android:id="@+id/button1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="@string/change" 
     android:layout_below="@+id/editTextAddress2" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentEnd="true" 
     android:layout_marginTop="30dp" 
     android:onClick="onBtnClicked"/> --> 


</RelativeLayout> 
</ScrollView> 

MainActivity

package com.androidbegin.absfragtabhost; 

import android.app.ActionBar; 
import android.app.Fragment; 
import android.os.Bundle; 
import android.app.Activity; 

public class MainActivity extends Activity { 
// Declare Tab Variable 
ActionBar.Tab Tab1, Tab2, Tab3; 
Fragment fragmentTab1 = new FragmentTab1(); 
Fragment fragmentTab2 = new FragmentTab2(); 
Fragment fragmentTab3 = new FragmentTab3(); 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    ActionBar actionBar = getActionBar(); 

    // Hide Actionbar Icon 
    actionBar.setDisplayShowHomeEnabled(false); 

    // Hide Actionbar Title 
    actionBar.setDisplayShowTitleEnabled(false); 

    // Create Actionbar Tabs 
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 

    // Set Tab Icon and Titles 
    Tab1 = actionBar.newTab().setIcon(R.drawable.tab1); 
    Tab2 = actionBar.newTab().setText("Tab2"); 
    Tab3 = actionBar.newTab().setText("Tab3"); 

    // Set Tab Listeners 
    Tab1.setTabListener(new TabListener(fragmentTab1)); 
    Tab2.setTabListener(new TabListener(fragmentTab2)); 
    Tab3.setTabListener(new TabListener(fragmentTab3)); 

    // Add tabs to actionbar 
    actionBar.addTab(Tab1); 
    actionBar.addTab(Tab2); 
    actionBar.addTab(Tab3); 
} 
} 
+0

Проблема заключается в том, что Android ищет реализацию addButtonClicked в вашей деятельности, а не в вашем фрагменте. См. Аналогичную проблему здесь http://stackoverflow.com/questions/21192386/android-fragment-onclick-button-method – Lucas

+0

Где я могу создать onClickListener? Немного смущаюсь над этим – user3375184

ответ

0

Трассировка говорит: «Не удалось найти метод addButtonClicked (View) в классе активности com.androidbegin.absfragtabhost.MainActivity для обработчика OnClick на вид класса android.widget.Button с идентификатором«addButtonClicked »

метод должен быть в классе активности не во фрагменте, либо поместить его туда или использовать onClickListener вместо (что бы я сделал)

как это:

Button addButtonClicked = (Button)rootView.findViewById(R.id.addButtonClicked); 
addButtonClicked.setOnClickListener(new OnClickListener(){ 
      public void onClick(View v) 
      { 
       addButtonClicked(v); //(you dont need this parameter though) 
      } 
}); 
+0

. Где я бы положил onClickListener? и любая идея, как его реализовать? Спасибо – user3375184

+0

В методе oncreateview в классе фрагмента, отредактировав ответ, чтобы показать, как это выглядит. – CyborgFish

+0

Итак, я получаю следующую ошибку: «невозможно разрешить корневое имя символа». Что мне делать с остальной частью кода, я могу оставить его в FragmentTab1 или? Как они соединяются? Извините за все вопросы, я новичок в фрагментах. спасибо – user3375184

Смежные вопросы