Reusing views on multiple activites in Android
-
26-05-2021 - |
Question
I have the following scenario: android up, compatible starting with android 1.6 and up. At the bottom of ALL activities I have a set of ToggleButtons that only start activities. Don't ask me why, that was the request :) Having these buttons do the same thing in all screens I thought like this:
- Put the layout in a xml file and it in all my activities layout
- Create a class that extends Activity and assign onClick methods for all my buttons
- When a ToggleButton is checked, set all other buttons checked="false" and perform the button's operation.
I am stuck on my BaseActivity, when overriding onCreate(). How do I get a hold of my buttons and assign onClick listeners to them ?
public class BaseActivity extends Activity {
private ToggleButton menuHome;
@Override
public void onCreate(Bundle savedInstanceState) {
//this does not work as it cannot find R.id.menu_home)
menuHome = (ToggleButton) findViewById(R.id.menu_home);
}
}
La solution
In your other Activities that extend BaseActivity take a look at your OnCreate method. Does it look like this?
public class YourActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
base.Oncreate(saveInstanceState);
setContentView(R.layout.YourLayout);
// Other code here...
}
}
It has to do with the order... you haven't set the content view so your toggle button doesn't exist. Try this:
public class YourActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.YourLayout); // Set your content view first.
base.Oncreate(saveInstanceState);
// Other code here...
}
}
Autres conseils
You need to initialize the GUI with a valid xml file or through runtime object initialization. Try using setContentView on your activity. Your code is not loading any xml, so there's no menu_home initialized.
http://developer.android.com/reference/android/app/Activity.html
I'm not sure if this is the right approach, I'd consider doing an external component to do the job: http://developer.android.com/guide/topics/ui/custom-components.html
You have to call setContentView(R.layout.your_layout) where your_layout is the layout containing the button R.id.menu_home. Right now you did not provide a layout to the activity so there is no hierarchy where to search for the button.