我在片段上编写代码时应用程序崩溃的原因

时间:2015-08-31 07:46:35

标签: android

我在片段中写了一些代码。当我这样写的时候工作正常吗?

public class Fragmentone  extends Fragment{

    ArrayList<String> name;
    boolean isPressed=false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, container, false);
        name=new ArrayList<String>();
        name.add("First Station");
        name.add("Second Station");


        ListView listView = (ListView) view.findViewById(R.id.list_view);



        ArrayAdapter arrayAdapter =new ArrayAdapter(getActivity(),R.layout.row_layout,R.id.station_name,name);
        listView.setAdapter(arrayAdapter);



        return view;
    }


}

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#325633">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list_view">
    </ListView>

</LinearLayout>

行布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/station_name"
        android:padding="10dp"
        android:textColor="#eee345"
        android:textAppearance="?android:textAppearanceLarge"
        />

    <ImageButton android:id="@+id/favorite"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:src="@drawable/start"
        android:background="#00ffffff"
        android:onClick="onToggleStar"/>


</LinearLayout>

但是当我添加图像按钮的点击事件时,它崩溃了为什么这里添加了图像点击事件代码..

public class Fragmentone  extends Fragment{

    ArrayList<String> name;
    boolean isPressed=false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, container, false);
        name=new ArrayList<String>();
        name.add("First Station");
        name.add("Second Station");


        ListView listView = (ListView) view.findViewById(R.id.list_view);
        ImageButton imageButton = (ImageButton) view.findViewById(R.id.favorite);
        imageButton.setBackgroundResource(R.drawable.off);

        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isPressed){
                    v.setBackgroundResource(R.drawable.off);
                }else{
                    v.setBackgroundResource(R.drawable.on);
                }
                isPressed = !isPressed; // reverse
            }
        });


        ArrayAdapter arrayAdapter =new ArrayAdapter(getActivity(),R.layout.row_layout,R.id.station_name,name);
        listView.setAdapter(arrayAdapter);



        return view;
    }


}

log cat

08-31 13:18:31.900  21769-21769/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.naveen.tabsfavourite, PID: 21769
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setBackgroundResource(int)' on a null object reference
            at com.example.naveen.tabsfavourite.Fragmentone.onCreateView(Fragmentone.java:34)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
            at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1105)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:951)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1473)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:447)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2615)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:550)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

更新代码

public class Fragmentone  extends Fragment{

    ArrayList<String> name;
    boolean isPressed=false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, container, false);
        name=new ArrayList<String>();
        name.add("First Station");
        name.add("Second Station");


        ListView listView = (ListView) view.findViewById(R.id.list_view);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String item = (String) parent.getItemAtPosition(position);
                Toast.makeText(getActivity(), "Item : " + item, Toast.LENGTH_SHORT).show();
            }
        });

        ArrayAdapter arrayAdapter =new ArrayAdapter(getActivity(),R.layout.row_layout,R.id.station_name,name);
        listView.setAdapter(arrayAdapter);



        return view;
    }


}



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#325633"
    android:descendantFocusability="blocksDescendants">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list_view">
    </ListView>

</LinearLayout>

2 个答案:

答案 0 :(得分:2)

这是因为ImageButton是ListView行的一部分,而不是Fragment的View的层次结构。在你的情况下

ImageButton imageButton = (ImageButton) view.findViewById(R.id.favorite);

返回空引用。要处理行的单击,您应该调用listView.setOnOnItemClickListener,传递实现AdapterView.OnItemClickListener的类的实例。

E.g

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
          String item = parent.getItemAtPosition(position);
          Toast.makeText(getActivity(), "Item : " + item, Toast.LENGTH_SHORT).show();                
       }
});

答案 1 :(得分:0)

问题是view.findViewById(R.id.favorite)无法找到具有该ID(最喜欢的)的图像视图。在布局R.layout.fragment_one中查找该图像ID,并确保存在。