当我使用带片段的onclicklistener时应用程序崩溃的原因?

问题描述 投票:-1回答:1
public class MainActivity extends AppCompatActivity {


    Context context;
    LinearLayout menuClcick,gallerClcik,eventsClick;
    LayoutInflater inflater;`enter code here`


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //we don't need to set view, our fragment will handle it

        setPointer();
        //Fragment Manger
        FragmentManager fm = getFragmentManager();
        //create instance of Fragment Transaction to handle fragment replace and animation
        FragmentTransaction ft=fm.beginTransaction();

        int displayMode = getResources().getConfiguration().orientation;
        Log.e("WTF", "onCreate: "+displayMode );
        //choose which fragment to display according to screen orientation
        if (displayMode==1) //portrait
        {

// that's the Fragment that I use to display a layout in the portrait and other layout in the landscape// 

            //create instance of our portrait fragment
            Fragment1 f1=new Fragment1();
            //change content of the screen to our new fragment
            ft.replace(android.R.id.content,f1);
        }
        else
        {
            Fragment2 f2=new Fragment2();
            ft.replace(android.R.id.content,f2);
        }
        //choose animation
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        //commit our changes
        ft.commit();
    }

    private void setPointer() {
        this.context=this;
        menuClcick=findViewById(R.id.menuClick);
        gallerClcik=findViewById(R.id.gallerClcik);
        eventsClick=findViewById(R.id.eventsClick);

//this is the problem the app have no problem to find the buttons but it stops working when I try to put onclick listener in it//

        menuClcick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "portrait", Toast.LENGTH_SHORT).show();
            }
        });
    }
android fragment onclicklistener landscape-portrait
1个回答
0
投票

您正在尝试访问尚未创建的视图。正如documentation lifecycle所示,您应该实现onCreateView()来扩充您的布局,并且只有您可以访问您的R.id.menuClick

所以基本上,你应该在setPointer()上调用你的onCreateView()方法。

© www.soinside.com 2019 - 2024. All rights reserved.