Need to handle click from NON-Activity( .java ) class

前端 未结 3 564
深忆病人
深忆病人 2021-01-19 18:43

i have one main Activity class which contains huge amount of code/data. So i want to make it short and readable so i want to create one .java file which handle the some func

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-19 19:08

    Try this is working for me . May help you also !

    NonActivityClass:

    public class NonActivityClass {
    
        Context context;
        View v;
        public NonActivityClass(Context context, View v) {
            this.context = context;
            this.v = v;
        }
    
        public void test() {
            Button btn = (Button) v.findViewById(R.id.btn);
            btn.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Toast.makeText(context, "Hello I am inside Non Activity Class",
                            1).show();
    
                }
            });
        }
    }
    

    MainActivity:

    public class MainActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            View v = getLayoutInflater().inflate(R.layout.activity_main, null);
            setContentView(v);
            NonActivityClass nac = new NonActivityClass(MainActivity.this, v);
            nac.test();
        }
    }
    

提交回复
热议问题