문제

에서 내 안드로이드 앱 ViewPager, 이,나 FragmentActivity 을 만들기 위한 ViewPager.

onCreate 방법도 설정 OnClickListenerButton.그러나 컴파일한 후에 내 응용 프로그램 추락했다.면 모두 제거 setOnClickListeners 니다.

당신이 나를 도울 수 있습니까?

public class MainActivity extends FragmentActivity {

    AdvicePageAdapter pageAdapter;

    Spinner categoriesSpinner;

    Button blueButton, greenButton, pinkButton, greyButton, yellowButton;

    private OnClickListener oclBtn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        List<Fragment> fragments = getFragments();

        pageAdapter = new AdvicePageAdapter(getSupportFragmentManager(), fragments);

        ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
        pager.setAdapter(pageAdapter);

        blueButton = (Button) findViewById(R.id.blueButton);
        greenButton = (Button) findViewById(R.id.greenButton);
        pinkButton = (Button) findViewById(R.id.pinkButton);
        greyButton = (Button) findViewById(R.id.greyButton);
        yellowButton = (Button) findViewById(R.id.yellowButton);

        oclBtn = new OnClickListener (){
            @Override
            public void onClick(View v){
            }
        };

        blueButton.setOnClickListener(oclBtn);
        greenButton.setOnClickListener(oclBtn);
        pinkButton.setOnClickListener(oclBtn);
        greyButton.setOnClickListener(oclBtn);
        yellowButton.setOnClickListener(oclBtn);

    }
}

내환

04-12 11:31:33.567: E/AndroidRuntime(2748): FATAL EXCEPTION: main
04-12 11:31:33.567: E/AndroidRuntime(2748): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.eugene.greatadvice/com.eugene.greatadvice.MainActivity}: java.lang.NullPointerException
04-12 11:31:33.567: E/AndroidRuntime(2748):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at android.os.Looper.loop(Looper.java:137)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at android.app.ActivityThread.main(ActivityThread.java:5103)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at java.lang.reflect.Method.invokeNative(Native Method)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at java.lang.reflect.Method.invoke(Method.java:525)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at dalvik.system.NativeStart.main(Native Method)
04-12 11:31:33.567: E/AndroidRuntime(2748): Caused by: java.lang.NullPointerException
04-12 11:31:33.567: E/AndroidRuntime(2748):     at com.eugene.greatadvice.MainActivity.onCreate(MainActivity.java:83)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at android.app.Activity.performCreate(Activity.java:5133)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-12 11:31:33.567: E/AndroidRuntime(2748):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
04-12 11:31:33.567: E/AndroidRuntime(2748):     ... 11 more

주요 레이아웃 파일:

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

    <TextView
        android:id="@+id/textViewAdvice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />


</RelativeLayout>

FragmentFile:

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

    <TextView
        android:id="@+id/categoriesTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft = "15dip"
        android:layout_marginTop = "15dip"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/categoriesTitle"
        android:textColor="@color/white"
        android:textSize="17sp" />

    <TextView
        android:id="@+id/setingsTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft = "15dip"
        android:layout_marginBottom = "15dip"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/settingsTitle"
        android:textColor="@color/white"
        android:textSize="35sp"/>

    <Spinner
        android:id="@+id/categorieSpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft = "15dip"
        android:layout_marginRight = "15dip"
        android:layout_marginTop = "15dip"
        android:layout_below="@+id/categoriesTitle"
        android:entries="@array/categories_array"
        android:background="@color/white"
        android:paddingTop="5dip"
        android:paddingBottom="5dip"
        android:textSize="17sp" />

    <TextView
        android:id="@+id/colorsTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/categorieSpinner"
        android:layout_below="@+id/categorieSpinner"
        android:layout_marginTop="20dp"
        android:text="@string/colorsTitle"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="@color/white"
        android:textSize="17sp" />

    <View
        android:id="@+id/colorsBG"
        android:layout_width="84dip"
        android:layout_height="84dip"
        android:layout_below="@+id/colorsTitle"
        android:layout_marginLeft = "13dip"
        android:layout_marginTop = "13dip"
        android:background="@color/white" />

    <Button
        android:id="@+id/blueButton"
        android:layout_width="80dip"
        android:layout_height="80dip"
        android:layout_marginLeft = "15dip"
        android:layout_marginTop = "15dip"
        android:layout_below="@+id/colorsTitle"
        android:background="@color/blue"
     />

    <Button
        android:id="@+id/greenButton"
        android:layout_width="80dip"
        android:layout_height="80dip"
        android:layout_marginLeft = "110dip"
        android:layout_marginTop = "15dip"
        android:layout_below="@+id/colorsTitle"
        android:background="@color/green"
     />

    <Button
        android:id="@+id/pinkButton"
        android:layout_width="80dip"
        android:layout_height="80dip"
        android:layout_marginLeft = "205dip"
        android:layout_marginTop = "15dip"
        android:layout_below="@+id/colorsTitle"
        android:background="@color/pink"
     />

    <Button
        android:id="@+id/greyButton"
        android:layout_width="80dip"
        android:layout_height="80dip"
        android:layout_marginLeft = "15dip"
        android:layout_marginTop = "110dip"
        android:layout_below="@+id/colorsTitle"
        android:background="@color/lightGrey"
     />

    <Button
        android:id="@+id/yellowButton"
        android:layout_width="80dip"
        android:layout_height="80dip"
        android:layout_marginLeft = "110dip"
        android:layout_marginTop = "110dip"
        android:layout_below="@+id/colorsTitle"
        android:background="@color/yellow"
     />

</RelativeLayout>

전체 활동 코드

package com.eugene.greatadvice;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Spinner;

public class MainActivity extends FragmentActivity {

    AdvicePageAdapter pageAdapter;

    Spinner categoriesSpinner;

    Button blueButton, greenButton, pinkButton, greyButton, yellowButton;

    View colorsBG;

    public OnClickListener oclBtn = new OnClickListener() 
    {
        @Override
        public void onClick(View v) 
        {
            if(v == blueButton)
            {
            }

            if(v == greenButton)
            {
            }

           if(v == pinkButton)
            {
            }

            if(v == greyButton)
            {
            }
           if(v == yellowButton)
            {
            }
        }
      };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        List<Fragment> fragments = getFragments();

        pageAdapter = new AdvicePageAdapter(getSupportFragmentManager(), fragments);

        ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
        pager.setAdapter(pageAdapter);

        colorsBG = findViewById(R.id.colorsBG);

        //init actions

        categoriesSpinner = (Spinner) findViewById(R.id.categorieSpinner);

        blueButton = (Button) findViewById(R.id.blueButton);
        greenButton = (Button) findViewById(R.id.greenButton);
        pinkButton = (Button) findViewById(R.id.pinkButton);
        greyButton = (Button) findViewById(R.id.greyButton);
        yellowButton = (Button) findViewById(R.id.yellowButton);

        blueButton.setOnClickListener(oclBtn);
        greenButton.setOnClickListener(oclBtn);
        pinkButton.setOnClickListener(oclBtn);
        greyButton.setOnClickListener(oclBtn);
        yellowButton.setOnClickListener(oclBtn);

    }


    private List<Fragment> getFragments(){
        List<Fragment> fList = new ArrayList<Fragment>();

        fList.add(SettingsFragment.newInstance(""));
        fList.add(AdviceFragment.newInstance(""));

        return fList;
    }

    private class AdvicePageAdapter extends FragmentPagerAdapter {
        private List<Fragment> fragments;

        public AdvicePageAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }
        @Override
        public Fragment getItem(int position) {
            return this.fragments.get(position);
        }

        @Override
        public int getCount() {
            return this.fragments.size();
        }
    }

}
도움이 되었습니까?

해결책

그러나 컴파일한 후에 내 응용 프로그램 추락했다.

NullPointerException 이 일어나고 있기 때문에 당신은에 액세스하려 보기 Fragment 에서 부적절한 시간 이지 않을 때에 유효한 상태입니다.이 버튼은 조각의 레이아웃,조각은 단지에 인스턴스화 onCreate() 콜백,뷰 생성됩 후에 방법 onCreate() 그래서 노력하는 사람들을 찾을 버튼 존재하지 않는 조각 보기를 만들 것입니다 참조은 null 입니다.

무슨 일을 하는 것은 또한 잘못 때문에 그것은 아주 좋은 방법을 처리하는 상호 작용입니다.조각해야하는 디자인으로 자기 포함된 항목,연결할 수 있는 곳이 필요하고,검색에 대한 조각의에서 보기 Activity 이와 관계의 조각이 Activity(을 언급하지 않은 높은 가능성의류).이를 방지하기 위해(와 함께 위의 문제)인터페이스를 사용하여 전송한 클릭에서 이벤트를 조각하면 이것은 당신이 원하는 무엇인가:

/**
* An interface that will transmit the click events to the Activity
*/
public interface ClickDispatch {

    void onClickReceived(View btn);
}

의 활동을 구현합니다 이 인터페이스

public class MainActivity extends FragmentActivity implements ClickDispatch {

   // code...

   @Override
   public void onClickReceived(View btn) {
       // one of the fragment's buttons(btn) was clicked so do stuff
   }

다음의 버튼과정에서 수신기에서 그들의 활동 onCreate() 는 방법을 조각을 버튼:

   ClickDispatch mListener; 

   // in the fragment class
   @Override
   public void onAttach(Activity activity) {
       super.onAttach(activity);
       // this is where the activity is passed to the fragment, we use this to cast the 
       // activity to our listener to pass it the click events
       mListener = (ClickDispatch) activity;
   } 


   // in the onCreateView method of the fragment:
   View inflatedView = inflater.inflate(/*your layout*/);
   blueButton = (Button) inflatedView.findViewById(R.id.blueButton);
   greenButton = (Button) inflatedView.findViewById(R.id.greenButton);
   pinkButton = (Button) inflatedView.findViewById(R.id.pinkButton);
   greyButton = (Button) inflatedView.findViewById(R.id.greyButton);
   yellowButton = (Button) inflatedView.findViewById(R.id.yellowButton);
   OnClickListener oclBtn = new OnClickListener (){
            @Override
            public void onClick(View v){
                // dispatch the click event to the Activity
                if (mListener != null) {
                     mListener.onClickReceived(v);
                }
            }
        };
   blueButton.setOnClickListener(oclBtn);
   greenButton.setOnClickListener(oclBtn);
   pinkButton.setOnClickListener(oclBtn);
   greyButton.setOnClickListener(oclBtn);
   yellowButton.setOnClickListener(oclBtn);

다른 팁

귀하의 버튼과 다른 전망되고 있는 팽창으로 조각하지,당신의 활동,그래서 findViewById() 으로 돌아 null 사람들을 위해 id 입니다.할 경우 의미에 대해,etc.야에서 활동,이동하는 요소에서 FragmentFile 하기 activity_main.xml.그렇지 않으면 이동하기 초기화 방법 및 귀하의 조각됩니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top