Is there a way I can use two classes or more for one Activity in android studio?

Is there a way I can use two classes or more for one Activity in android studio? I used this Test code but this App crashes:

Note : This is for learning purposes so that it can be used to split up huge classes into sub classes //Main Activity Class

public class MainActivity extends AppCompatActivity  {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Test ob=new Test ();
  ob.test();
}

}

// Test Class

public class Test extends MainActivity {
public void test()
{
    TextView t=findViewById(R.id.h);
    t.setText("Miaooo");
}

}

Answer

What you can do is to pass the activity with as the parameter of constructor and use that reference to call “findViewbyId()”

public class Test{
public void test(Activity activity)
{
    TextView t=activity.findViewById(R.id.h);
    t.setText("Miaooo");
}

while in your main activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Test ob=new Test (this);
  ob.test();
}

If you want to your “Test” class to be extended by an activity than you should use activity creation wizard to setup all the stuff in manifest and .xml. It would be quite long process to do it manually.

Leave a Reply

Your email address will not be published. Required fields are marked *