【问题标题】:android:onClick = "functionName" did not recognize the function name in Fragment subclassandroid:onClick = "functionName" 无法识别 Fragment 子类中的函数名
【发布时间】:2016-09-12 21:31:30
【问题描述】:

我的布局xml文件中Buttonandroid:onClick = "clickFun1"无法识别DipToVol extends Fragment类中提到的clickFun1()方法。 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>

请告诉我哪里做错了。当我运行代码时,应用程序崩溃了。错误日志显示 clickFun1() 未找到。

//日志猫

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 ...

【问题讨论】:

  • 如果在包含 Fragment 的 Activity 中移动 clickFun1() 方法会怎样?
  • @Rotwang 我确实将 clickFun1() 方法移到 mainActivity.java 中,只留下我的 DipToVol 类用于 onCreateView 来扩充片段布局文件。当我单击按钮时,应用程序仍然崩溃。
  • 当你说 app crashing 时,你至少应该发布你的 logcat。
  • @Rotwang 相同的代码在没有片段和标签的应用程序中运行良好。那是简单的计算器。这次我将两个这样的计算器的代码分成两个片段(两个选项卡/滑动视图)。该应用程序正在打开,所有片段布局都很好,但是当我单击任何按钮时,它就崩溃了。
  • logcat 请... it is crashing 没有任何意义。

标签: android xml


【解决方案1】:

这不是错误。 (方法警告,而不是应用程序崩溃)。 Java 编译器不知道您在 XML 中定义了监听器,因此由于您从未显式调用这些方法,它只是认为它们“从未使用过”

就我个人而言,我总是在 Java 代码的视图中设置 OnClickListener

【讨论】:

  • 当我运行这个时,应用程序正在打开并显示布局,但是当我点击其中任何一个 clickFun1 或 clearFun1 时,应用程序正在崩溃。 Logcat 说在父级或祖先级找不到 clickFun1 函数。当我在 OnCreateView 内的按钮上使用 setOnClickListener 时,应用程序在打开后立即崩溃。
  • @SivaPrasad:“当我在 OnCreateView 内的按钮上使用 setOnClickListener 时,应用程序在打开后立即崩溃”——询问一个单独的 Stack Overflow 问题,您可以在其中提供 此代码这个 Java 堆栈跟踪
  • @CommonsWare 上次我发布了一个类似的问题,android studio 没有警告我该方法从未使用过。但是今天,当我编辑了一些代码并且发现它不起作用时,我来到了初始代码,这次 AS 发出警告。
  • @SivaPrasad CommonsWare 已经回答了您之前接受的问题,他(以及我)建议删除 XML 点击监听器以支持设置@ 987654321@通过Java
  • @SivaPrasad - 也许您尝试了 Java 代码并忘记删除 XML 设置?当您尝试设置侦听器时,也许您在 Fragment 中错误地从 XML 中找到了按钮?等等...如果没有看到应用程序崩溃的原因,很难知道问题是什么,但它的错误消息肯定会与您当前的不同
【解决方案2】:

当 Android 正在运行并检查 onClick 方法时,它只会在主 Activity 类中查找。您不能在片段中放置 onClick 方法。碎片不等同于活动,所以不应该被滥用。

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

【讨论】:

  • 您确实意识到您链接的帖子是由与此帖子相同的用户询问的,是吗?
  • @cricket_007 我尝试了 commonsware 的建议。我首先使用 onClickListener 尝试了第一个。但是应用程序立即崩溃。接下来我尝试了第二个建议,将 onClick 保持在 xml 布局中。但它的发生方式与我在上一个问题中引用的方式相同,即单击任何按钮时都会崩溃。然后我尝试将所有代码移动到 mainActivity.java 并在按钮上使用 onClickListeners。这一次甚至在显示布局之前就再次崩溃。
  • @cricket_007 那么这些是重复的问题。感谢您指出这一点。
【解决方案3】:

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

tools:context=".MainActivity"

【讨论】:

  • 除了 IDE 编辑器控制的活动之外,它实际上不控制任何东西。编译应用时将其删除
【解决方案4】:

正如其他用户所说。您不能将onClick 属性与片段一起使用。但是这个宇宙有 Jake Wharton 和他很棒的图书馆,包括 Butterknife。 Check this out.

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多