android:onClick =“functionName”无法识别Fragment子类中的函数名称

时间:2016-09-11 17:28:39

标签: android xml

我的布局xml文件中android:onClick = "clickFun1"

Button无法识别clickFun1()类中提到的DipToVol extends Fragment方法。 Android Studio表示该方法无处使用。

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

    public double calVol(short rad, short len, int height) {
        double area;
        area = (Math.PI * Math.pow(rad, 2) / 2) - Math.pow(rad, 2) * Math.asin(1 - (height / (double)rad)) - (rad - height) * Math.sqrt(height * (2 * rad - height));
        return area*len*0.000001;
    }

    //here android studio says this method never used
    public void clickFun1 (View view)
    {
        int dipHSD = 0, dipMS = 0;
        final short radHSD = 1219;
        final short lenHSD = 6810;
        final short radMS = 999;
        final short lenMS = 6804;
        double volHSD, volMS;

        EditText dipH = (EditText) view.findViewById(R.id.dipHSD1);
        EditText dipM = (EditText) view.findViewById(R.id.dipMS1);

        TextView volH = (TextView) view.findViewById(R.id.volHSD1);
        TextView volM = (TextView) view.findViewById(R.id.volMS1);
        try {
            dipHSD = Integer.parseInt(dipH.getText().toString());
            volHSD = calVol(radHSD, lenHSD, dipHSD);
            volHSD = Math.round(volHSD);
            volH.setText(volHSD + "");
        }
        catch (NumberFormatException e) {
            volH.setText("");
        }
        try{ dipMS = Integer.parseInt(dipM.getText().toString());
            volMS = calVol(radMS, lenMS, dipMS);
            volMS = Math.round(volMS);
            volM.setText(volMS + "");
        }catch(NumberFormatException e){volM.setText("");}

    }

    //here android studio says this method never used
    public void clearFun1(View view){
        EditText dipH = (EditText) view.findViewById(R.id.dipHSD1);
        EditText dipM = (EditText) view.findViewById(R.id.dipMS1);

        TextView volH = (TextView) view.findViewById(R.id.volHSD1);
        TextView volM = (TextView) view.findViewById(R.id.volMS1);

        volH.setText("");
        volM.setText("");
        dipH.setText("");
        dipM.setText("");
   } 

}

fragment_one.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/section_label1"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    android:background="#4ab4b2">


       <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/contentView"
        android:layout_weight ="1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
           android:layout_alignParentBottom="false"
           android:layout_alignParentRight="false"
           android:layout_alignWithParentIfMissing="false">

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="HSD Dip"
                android:id="@+id/lableDipHSD"
                android:layout_column="0"
                android:textSize="30sp"
                android:textStyle="bold"
                android:textColor="#ffffff"
                android:layout_marginLeft="5dp" />

            <EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:ems="10"
                android:id="@+id/dipHSD1"
                android:textSize="30sp"
                android:textStyle="bold"
                android:layout_column="1"
                android:textColor="#ffffff"
                />
        </TableRow>

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="MS Dip"
                android:id="@+id/lableDipMS"
                android:layout_column="0"
                android:textSize="30sp"
                android:textStyle="bold"
                android:textColor="#ffffff"
                android:layout_marginLeft="5dp" />

            <EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:id="@+id/dipMS1"
                android:layout_column="1"
                android:textStyle="bold"
                android:textSize="30sp"
                android:textColor="#ffffff"
                />
        </TableRow>

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="HSD Volume"
                android:id="@+id/lableVolHSD"
                android:layout_column="0"
                android:textStyle="bold"
                android:textSize="30sp"
                android:paddingTop="15dp"
                android:textColor="#ffffff"
                android:layout_marginLeft="5dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/volHSD1"
                android:layout_column="1"
                android:textStyle="bold"
                android:textSize="30sp"
                android:textColor="#ffffff" />
        </TableRow>

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="MS Volume"
                android:id="@+id/lableVolMS"
                android:layout_column="0"
                android:textStyle="bold"
                android:textSize="30sp"
                android:paddingTop="15dp"
                android:textColor="#ffffff"
                android:layout_marginLeft="5dp"
                android:paddingBottom="10dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/volMS1"
                android:layout_column="1"
                android:textStyle="bold"
                android:textSize="30sp"
                android:textColor="#ffffff"
                android:paddingBottom="10dp" />
        </TableRow>

    </TableLayout>




    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/clearBtn"
        android:id="@+id/clearBtn1"
        android:textSize="25sp"
        android:clickable="true"
        android:onClick="clearFun1"
        android:background="#fa0690"
        android:padding="8dp"
        android:paddingLeft="8dp"
        android:paddingTop="2dp"
        android:paddingRight="8dp"
        android:paddingBottom="2dp"
        android:textAlignment="center"
        android:textStyle="bold"
        android:layout_column="0"
        android:layout_below="@+id/contentView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="40dp"
        android:layout_toStartOf="@+id/calcBtn1"
        android:layout_toLeftOf="@+id/calcBtn1"
        android:alpha="0.8"
        android:layout_marginRight="10dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/calcBtn"
        android:id="@+id/calcBtn1"
        android:textSize="25sp"
        android:clickable="true"
        android:onClick="clickFun1"
        android:background="#fa0690"
        android:padding="8dp"
        android:paddingLeft="8dp"
        android:paddingTop="2dp"
        android:paddingRight="8dp"
        android:paddingBottom="2dp"
        android:textAlignment="center"
        android:textStyle="bold"
        android:layout_column="0"
        android:layout_alignTop="@+id/clearBtn1"
        android:layout_alignRight="@+id/contentView"
        android:layout_alignEnd="@+id/contentView"
        android:alpha="0.8" />

</RelativeLayout>

请告诉我我做错了什么。当我运行代码时,App正在崩溃。错误日志显示找不到clickFun1()

// logcat

09-10 13:49:24.823 2718-2718/com.example.siv.mahalaxmipetroleums E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                   java.lang.IllegalStateException: Could not find method clickFun1(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'calcBtn'
                                                                                       at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
                                                                                       at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                                                                                       at android.view.View.performClick(View.java:4240)
                                                                                       at android.view.View$PerformClick.run(View.java:17721)
                                                                                       at android.os.Handler.handleCallback(Handler.java:730)
                                                                                       at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                                       at android.os.Looper.loop(Looper.java:137)
                                                                                       at android.app.ActivityThread.main(ActivityThread.java:5103)
                                                                                       at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                       at java.lang.reflect.Method.invoke(Method.java:525)
                                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
                                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                                                       at dalvik.system.NativeStart.main(Native Method)

我已更改mainActivity.java,如下所示。将代码从片段子类移动到mainActivity.java

package com.example.siv.mahalaxmipetroleums;

import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;


    Button clearBtn_f1,calcBtn_f1,clearBtn_f2,calcBtn_f2;



    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        clearBtn_f1 = (Button) findViewById(R.id.clearBtn1);
        clearBtn_f2 = (Button) findViewById(R.id.clearBtn2);
        calcBtn_f1 = (Button) findViewById(R.id.calcBtn1);
        calcBtn_f2 = (Button) findViewById(R.id.calcBtn2);

        clearBtn_f1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearFun1(v);
            }
        });
        clearBtn_f2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearFun2(v);
            }
        });

        calcBtn_f1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickFun1(v);
            }
        });

        calcBtn_f2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickFun2(v);
            }
        });


         }


    @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);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
   public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
        // */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

      /*  @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_one, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }*/
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).

           if (position == 0) {
                return new Fragment_One();
            } else if (position == 1) {
                return new Fragment_Two();
            } else
                return new Fragment_Three();//PlaceholderFragment.newInstance(position + 1);

        }
        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Dip-Vol";
                case 1:
                    return "Vol-Dip";
                case 2:
                    return "Temp-Dens";
            }
            return null;
        }
    }

    public void clickFun1 (View view)
    {
        short dipHSD = 0, dipMS = 0;
        final short radHSD = 1219;
        final short lenHSD = 6810;
        final short radMS = 999;
        final short lenMS = 6804;
        double volHSD, volMS;

        EditText dipH = (EditText) view.findViewById(R.id.dipHSD1);
        EditText dipM = (EditText) view.findViewById(R.id.dipMS1);

        TextView volH = (TextView) view.findViewById(R.id.volHSD1);
        TextView volM = (TextView) view.findViewById(R.id.volMS1);
        try {
            dipHSD = Short.parseShort(dipH.getText().toString());
            Liquid_Volume dtvh = new Liquid_Volume(radHSD,lenHSD,dipHSD);
            volHSD = dtvh.getVolume();
            volHSD = Math.round(volHSD);
            volH.setText(volHSD + "");
        }
        catch (NumberFormatException e) {
            volH.setText("");
        }
        try{ dipMS = Short.parseShort(dipM.getText().toString());
            Liquid_Volume dtvm = new Liquid_Volume(radMS,lenMS,dipMS);
            volMS = dtvm.getVolume();
            volM.setText(volMS + "");
        }catch(NumberFormatException e){volM.setText("");}

    }

    public void clearFun1(View view){
        EditText dipH = (EditText) view.findViewById(R.id.dipHSD1);
        EditText dipM = (EditText) view.findViewById(R.id.dipMS1);

        TextView volH = (TextView) view.findViewById(R.id.volHSD1);
        TextView volM = (TextView) view.findViewById(R.id.volMS1);

        volH.setText("");
        volM.setText("");
        dipH.setText("");
        dipM.setText("");
    }

    public void clickFun2 (View view)
    {
        EditText volH = (EditText) view.findViewById(R.id.volHSD2);
        EditText volM = (EditText) view.findViewById(R.id.volMS2);

        TextView dipH = (TextView) view.findViewById(R.id.dipHSD2);
        TextView dipM = (TextView) view.findViewById(R.id.dipMS2);

        double volHSD = 0, volMS = 0;
        final double radHSD = 121.9;
        final double lenHSD = 681.0;
        final double radMS = 99.9;
        final double lenMS = 680.4;
        double dipHSD, dipMS;

        try {
            volHSD = Double.parseDouble(volH.getText().toString());
            Liquid_Height HSD = new Liquid_Height(radHSD,lenHSD,volHSD);
            dipHSD = HSD.getDip();
            //String.format("%f",dipHSD);
            //dipH.setText(Double.toString(dipHSD));
            dipH.setText(dipHSD + "");
        }
        catch (NumberFormatException e) {
            dipH.setText("");
        }
        try{ volMS = Double.parseDouble(volM.getText().toString());
            Liquid_Height MS = new Liquid_Height(radMS,lenMS,volMS);
            dipMS = MS.getDip();
            //String.format("%f",dipHSD);
            //dipM.setText(String.format("%f",dipMS));
            dipM.setText(dipMS + "");
        }
        catch(NumberFormatException e){
            dipM.setText("");
        }

    }

    public void clearFun2(View view){
        EditText volH = (EditText) view.findViewById(R.id.volHSD2);
        EditText volM = (EditText) view.findViewById(R.id.volMS2);

        TextView dipH = (TextView) view.findViewById(R.id.dipHSD2);
        TextView dipM = (TextView) view.findViewById(R.id.dipMS2);

        volH.setText("");
        volM.setText("");
        dipH.setText("");
        dipM.setText("");
    }

}

然后我有了fragment_one.java并以同样的方式休息其他片段。

public class Fragment_One extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_one, container, false);

    }

}

此处应用程序在我尝试打开后立即崩溃。

Logcat说以下

09-12 07:17:40.600 2283-2291/com.google.android.gms E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
                                                                  java.lang.Throwable: Explicit termination method 'close' not called
                                                                      at dalvik.system.CloseGuard.open(CloseGuard.java:184)
                                                                      at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:190)
                                                                      at ...

4 个答案:

答案 0 :(得分:1)

这不是错误。 (方法警告,而不是应用程序崩溃)。 Java编译器不知道你已经在XML中定义了监听器,所以既然你从未明确地调用这些方法,它只是认为它们“从不使用”

就个人而言,我总是在Java代码

的视图上设置OnClickListener

答案 1 :(得分:1)

当Android运行并检查onClick方法时,它只在主Activity类中查找。您无法在片段中放置onClick方法。碎片与活动不同,因此不应滥用它们。

另一个问题在这里有同样的问题:https://stackoverflow.com/a/39429157/6754053

答案 2 :(得分:0)

正如其他用户所说。您不能将onClick属性与Fragments一起使用。但这个宇宙拥有杰克沃顿和他令人敬畏的图书馆,包括Butterknife。 Check this out.

答案 3 :(得分:0)

从布局的根目录中删除此行可能会有所帮助;

tools:context=".MainActivity"