在Android Java中重用onclick侦听器和字符串参数

时间:2016-02-19 04:54:11

标签: java android eclipse onclicklistener

我正在模仿此thread中的代码,以创建一个可重复使用的点击事件来触发浏览器。我想在实例化类时传递自定义URL目标。该示例在eclipse中没有明显错误,但在启动时崩溃:

btn.setOnClickListener(new ButtonInternetAccess("http://google.com"));

错误应来自此行 ButtonInternetAccess

因为没有那条线它可以正常工作。 类public class ItemActivity extends ActionBarActivity{ private static final View View = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item); Bundle b = i.getExtras(); Button btn = (Button) findViewById(R.id.button_internet_access); btn.setOnClickListener(new ButtonInternetAccess("http://google.com")); } } 是否无法返回导致null值的onClickListener?我该如何解决这个问题?

主要活动:

public class ButtonInternetAccess extends Activity implements OnClickListener {
    String url;
    public ButtonInternetAccess(String url) {
        this.url = url;
    }

    public void onClick(View v) {
        try {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse(url));
            startActivity(callIntent); // No Error here

            System.out.println(url);
        } catch (ActivityNotFoundException activityException) {
            Log.e("Calling a Phone Number", "Call failed", activityException);
        }
    }

}

按钮类:

<TextView
    android:id="@+id/response"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="" />

<include android:id="@+id/header" layout="@layout/button_internet_access">

布局/ activity_item

<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/button_internet_access"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="go out" />

布局/ button_internet_access:

02-19 12:45:57.416: E/AndroidRuntime(12465): FATAL EXCEPTION: main
02-19 12:45:57.416: E/AndroidRuntime(12465): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app/com.app.ItemActivity}: java.lang.NullPointerException
02-19 12:45:57.416: E/AndroidRuntime(12465):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at android.app.ActivityThread.access$600(ActivityThread.java:130)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at android.os.Looper.loop(Looper.java:137)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at android.app.ActivityThread.main(ActivityThread.java:4745)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at java.lang.reflect.Method.invokeNative(Native Method)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at java.lang.reflect.Method.invoke(Method.java:511)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at dalvik.system.NativeStart.main(Native Method)
02-19 12:45:57.416: E/AndroidRuntime(12465): Caused by: java.lang.NullPointerException
02-19 12:45:57.416: E/AndroidRuntime(12465):    at com.app.ItemActivity.onCreate(ItemActivity.java:29)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at android.app.Activity.performCreate(Activity.java:5008)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
02-19 12:45:57.416: E/AndroidRuntime(12465):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)

错误:

public class Internet implements OnClickListener {

    private String url;
    private Context context;

    public Internet(Context context, String url) {
        this.context = context;
        this.url = url;
    }

    @Override
    public void onClick(View v) {

        if (!url.contains("http://")){
            url = "http://"+url;
        }
        Intent callIntent = new Intent(Intent.ACTION_VIEW);
        callIntent.setData(Uri.parse(url));
        context.startActivity(callIntent);
    }
}

更新:

我已设法在此link之后制作插件。

最后的工作:

班级互联网:

public class StyleButton extends Button{

    public StyleButton(Context context) {
        super(context);
    }

    public StyleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        initStyleButton(attrs);
    }

    public StyleButton(Context context, AttributeSet attrs, int defStyle,String url) {
        super(context, attrs, defStyle);
        initStyleButton(attrs);
    }

    private void initStyleButton(AttributeSet attrs){
        TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.style_Button);
        String Text1 = a.getString(R.styleable.style_Button_myText_1);
        String Text2 = a.getString(R.styleable.style_Button_myText_2);
        setText(Text1 + "\n" + Text2);
        String url = a.getString(R.styleable.style_Button_url);
        System.out.println(url);
        setOnClickListener(new Internet(getContext(),url));
        a.recycle();
    }
}

Class StyleButton:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:stylebutton= "http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:id="@+id/response"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text=""/>
<com.button.StyleButton
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    stylebutton:myText_1="My Text 1"
    stylebutton:myText_2="My Text 2"
    stylebutton:url="www.google.com"
    />
<com.button.StyleButton
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    stylebutton:myText_1="Hello!"
    stylebutton:myText_2="It's a Style Button:)"
    stylebutton:url="www.yahoo.com"
    />

/布局/ item_activity

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="style_Button">
        <attr name="myText_1" format="string" />
        <attr name="myText_2" format="string" />
        <attr name="url" format="string" />
    </declare-styleable>
</resources>

/value/attr.xml

<button class="btn btn-default" id="1" onclick="APP.agregarNumeros()">1</button>
<button class="btn btn-default" id="2" onclick="APP.agregarNumeros()">2</button>
<p id="resultado"></p>

<script>    
var counterAPP = {
        agregarNumeros:function(){
            var resultado = "";
            if ($("#1")) {
                resultado += $("#resultado").text("1");
            }
            else if ($("#2")) {
                resultado += $("#resultado").text("2");
            }
        }
    };
    window.APP = counterAPP;

3 个答案:

答案 0 :(得分:1)

将按钮类更改为;

{{1}}

答案 1 :(得分:1)

你的setOnClickListener应如下所示:

btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Intent callIntent = new Intent(Intent.ACTION_CALL);
                    callIntent.setData(Uri.parse("http://google.com"));
                    startActivity(callIntent); // No Error here
                    System.out.println(url);
                } catch (ActivityNotFoundException activityException) {
                    Log.e("Calling a Phone Number", "Call failed", activityException);
                }
            }
        });

您似乎不需要将URL发送到另一个类,因为您可以对ItemActivity本身执行相同的操作。

编辑:如果您想要将一个类格式化,请将ButtonInternetAccess更新为以下方式:

public class ButtonInternetAccess implements OnClickListener {
    String url;
    Context mContext;
    public ButtonInternetAccess(Context mContext,String url) {
        this.url = url;
        this.mContext=mContext;
    } 

    public void onClick(View v) {
        try { 
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse(url));
            mContext.startActivity(callIntent);

            System.out.println(url);
        } catch (ActivityNotFoundException activityException) {
            Log.e("Calling a Phone Number", "Call failed", activityException);
        } 
    } 

} 

答案 2 :(得分:1)

创建您的custom button并在项目中使用它,以便可以全局使用它。

    public class ButtonInternetAccess extends UIButton implements OnClickListener {
        String url;
    Context mContext;
    public ButtonInternetAccess(Context context, AttributeSet attrs,String url) {
            super(context, attrs);
         this.url = url;
        this.mContext=mContext;
            // TODO Auto-generated constructor stub
        }
        // initialize button and add click listener here.

}

您可以将该按钮添加到xml中,如

<yourpackagename.ButtonInternetAccess 
height=""
width = ""
other properties to include
/>
希望这会有所帮助。