簡體   English   中英

Android上的setOnClickListener錯誤

[英]Error on setOnClickListener Android

我正在為按鈕創建setOnClickListener 但這正在制造問題。
當我評論setOnClickListener部分時,代碼工作正常。
這是我的代碼:

public class Sales extends ActionBarActivity {

    Button btnBuy;
    Button btnSell;

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

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }


        btnBuy = (Button) findViewById(R.id.btn_buy);
        btnSell = (Button) findViewById(R.id.btn_sell);

        btnBuy.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Sales.this, Buy.class);
                startActivity(intent);      
                finish();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.sales, 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();
        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 {

        public PlaceholderFragment() {
        }

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

}  

我的activity_sales.xml是:

<FrameLayout 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"
    tools:context="com.example.tcshackathon.Sales"
    tools:ignore="MergeRootFrame" />  

我的fragment_sales.xml是:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.tcshackathon.Sales$PlaceholderFragment" >



    <Button android:id="@+id/btn_buy"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Buy Something"
                android:layout_marginTop="30dip"
                android:layout_gravity="center_horizontal"
                />

    <Button android:id="@+id/btn_sell"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/btn_logout"
                android:text="Sell Something"
                android:layout_marginTop="30dip"
                android:layout_gravity="center_horizontal"
                />

</LinearLayout>  

堆棧跟蹤 :

03-14 17:59:26.135: E/AndroidRuntime(15741): FATAL EXCEPTION: main
03-14 17:59:26.135: E/AndroidRuntime(15741): Process: com.example.tcshackathon, PID: 15741
03-14 17:59:26.135: E/AndroidRuntime(15741): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tcshackathon/com.example.tcshackathon.Buy}: java.lang.NullPointerException
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.ActivityThread.access$800(ActivityThread.java:139)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.os.Handler.dispatchMessage(Handler.java:102)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.os.Looper.loop(Looper.java:136)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.ActivityThread.main(ActivityThread.java:5102)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at java.lang.reflect.Method.invokeNative(Native Method)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at java.lang.reflect.Method.invoke(Method.java:515)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at dalvik.system.NativeStart.main(Native Method)
03-14 17:59:26.135: E/AndroidRuntime(15741): Caused by: java.lang.NullPointerException
03-14 17:59:26.135: E/AndroidRuntime(15741):    at com.example.tcshackathon.Buy.onCreate(Buy.java:93)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.Activity.performCreate(Activity.java:5248)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
03-14 17:59:26.135: E/AndroidRuntime(15741):    ... 11 more

我正在獲取Java.lang.NullPointerException。

有人可以告訴我為什么會這樣嗎?

在您的評論中,您說btn_buy屬於fragment_sales.xml 所以你需要在Fragment onCreateView中初始化按鈕

Button btnBuy,btnSell;
@Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_sales,
                container, false);
        btnBuy = (Button)rootView.findViewById(R.id.btn_buy);
        btnSell = (Button)rootView.findViewById(R.id.btn_sell); 
        btnBuy.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), Buy.class);
            startActivity(intent);      
            finish();
        }
        }); 
        return rootView;
 }

這些按鈕不屬於activity_sales.xml 因此,您的初始化失敗導致NullPointerException

編輯:

自從您更新了帖子以來,就有NPE @ 93行Buy.java 修理它。 現在發布的代碼很好。

btnBuy = (Button) findViewById(R.id.btn_buy);

btn_buy不屬於activity_sales.xml ,因此在findViewById()之后btnBuy值為null

不確定,但請嘗試

 btnBuy.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Sales.this, Buy.class);
            startActivity(intent);      
            finish();
        }
    });

將view.onclicklistener替換為onclicklistener

只需參考此鏈接

http://www.vogella.com/tutorials/AndroidActionBar/article.html

您可以將onOptionsItemSelected()方法用於buttonclick操作。

您可以遵循的另一種方法是:直接使用

 android:onClick="@string/buy_click"

在XML和Class中使用

  public void buy_click(View v){

/ ...在這里工作。/ }

我不知道這是否是編程的好方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM