【问题标题】:how can I define method in fragment?如何在片段中定义方法?
【发布时间】:2015-04-24 04:04:23
【问题描述】:

我在扩展 Activity 时尝试了这段代码,它运行 (Y),但是当我粘贴到这里扩展片段时,它给了我这个异常:

java.lang.IllegalStateException:在视图类 android.widget.Button 上的 id 为“scanner”的活动类 com.example.pc_orbit.myapplication.Citizen 中找不到方法 scanQR(View)

公共类报告扩展片段

{

static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";
@Override
public View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container,@Nullable Bundle savedInstanceState){
   // String s= getIntent().getExtras().getString("info");
    View v=  inflater.inflate(R.layout.report, container, false);
    return v;
}
public void  scanQR(View v) {
    try {
        //start the scanning activity from the com.google.zxing.client.android.SCAN intent
        Intent intent = new Intent(ACTION_SCAN);
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, 0);
    } catch (ActivityNotFoundException anfe) {
        //on catch, show the download dialog
        showDialog(getActivity(), "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
    }
}
private static AlertDialog showDialog(final Activity act, CharSequence title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo) {
    AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
    downloadDialog.setTitle(title);
    downloadDialog.setMessage(message);
    downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int i) {
            Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            try {
                act.startActivity(intent);
            } catch (ActivityNotFoundException anfe) {

            }
        }
    });
    downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int i) {
        }
    });
    return downloadDialog.show();
}
//on ActivityResult method
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 0) {
        if (resultCode == Activity.RESULT_OK) {
            //get the extras that are returned from the intent
            String contents = intent.getStringExtra("SCAN_RESULT");
            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
            Toast toast = Toast.makeText(getActivity(), "Content:" + contents + " Format:" + format, Toast.LENGTH_LONG);
            toast.show();
        }
    }
}

}

这是在扩展 Activity 时运行的代码

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.ActivityNotFoundException;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Toast;

公共类 AndroidQrCodeExample 扩展 Activity {

static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";

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

}

public void scanQR(View v) {
    try {
        //start the scanning activity from the com.google.zxing.client.android.SCAN intent
        Intent intent = new Intent(ACTION_SCAN);
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, 0);
    } catch (ActivityNotFoundException anfe) {
        //on catch, show the download dialog
        showDialog(AndroidQrCodeExample.this, "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
    }
 }

private static AlertDialog showDialog(final Activity act, CharSequence title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo) {
    AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
    downloadDialog.setTitle(title);
    downloadDialog.setMessage(message);
    downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int i) {
            Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            try {
                act.startActivity(intent);
            } catch (ActivityNotFoundException anfe) {

            }
        }
    });
    downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int i) {
        }
    });
    return downloadDialog.show();
}

//on ActivityResult method
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            //get the extras that are returned from the intent
            String contents = intent.getStringExtra("SCAN_RESULT");
            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
            Toast toast = Toast.makeText(this, "Content:" + contents + " Format:" + format, Toast.LENGTH_LONG);
            toast.show();
        }
    }
}

}

xml

    <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    tools:context="com.javacodegeeks.androidstartactivityforresultexample.ActivityOne" >

<TextView

    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center|top"
    android:layout_margin="20dp"
    android:text="Scan"
    android:textColor="#000000"
    android:textSize="30dp" />

<Button
    android:id="@+id/scanner"
    android:layout_width="250dp"
    android:layout_height="80dp"
    android:layout_gravity="center"
    android:layout_margin="10dp"
    android:gravity="center"
    android:onClick="scanQR"
    android:text="QR Code"
    android:textSize="18dp" >
    </Button>

<Button
    android:id="@+id/scanner2"
    android:layout_width="250dp"
    android:layout_height="80dp"
    android:layout_gravity="center"
    android:layout_margin="10dp"
    android:gravity="center"
    android:onClick="scanBar"
    android:text="Bar Code"
    android:textSize="18dp" >
    </Button>
    </LinearLayout>

【问题讨论】:

  • 你在哪里调用 scanQR() 方法?问题不在您发布的代码中。
  • 你在哪里使用 scanQR() ?在一个 xml 中?发布它。
  • @ElodieFerrais 检查 xml

标签: android methods fragment zxing


【解决方案1】:

XML-Layout 中定义的 onClick 方法总是在片段附加到的活动上调用。你必须在那里处理它。

这个话题经常被讨论: How to handle button clicks using the XML onClick within Fragments

【讨论】:

    【解决方案2】:

    点击会在活动中触发,但不会在片段中触发。因为您的布局中只有 2 个按钮(并且因为我认为这是最佳做法)

    建议你在fragment的onCreate方法中设置按钮监听。

    public class Report extends Fragment implements View.OnClickListener{
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v=  inflater.inflate(R.layout.report, container, false);
    
        Button scannerButton = (Button) v.findViewById(R.id.scanner);
        Button scanner2Button = (Button) v.findViewById(R.id.scanner2);
    
        scannerButton.setOnClickListener(this);
        scanner2Button.setOnClickListener(this);
    
        return v;
    }
    
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.scanner) {
            scanQR(v);
        } else if (v.getId() == R.id.scanner2) {
            scanBar(v);
        }
    }
    

    【讨论】:

    • 我们应该在扩展片段时覆盖 onCreateView,但它没有任何作用! :(
    • 是的!但它确实应该工作。您是否从 xml 中删除了 android:onClick="scanQR" 和 android:text="QR Code" ?你还有同样的例外吗?
    • 我删除了 android:onClick="scanQR" 并且有一个异常:java.lang.RuntimeException: Unable to instance activity ComponentInfo{com.examples.pc_orbit.testfragment/com.examples.pc_orbit.testfragment .Report}:java.lang.ClassCastException:com.examples.pc_orbit.testfragment.Report 无法转换为 android.app.Activity
    • 如何使用报表片段?您如何将其包含在您的活动中?
    • 你能帮我解决我的新问题吗:D stackoverflow.com/questions/29044997/…
    猜你喜欢
    • 2019-08-22
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 2014-10-09
    • 2013-10-13
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多