How can I use the same XML layout for different activities? - java

I am making a quiz app which includes 50 different quizzes. I have a basic quiz layout with buttons and text views, and I want to use this layout with all my activities. For example, if the player choose the first quiz, the layout should come automatically and my Java code should provide the corresponding answers/questions. How can I do this?

Put layout id in setContentView(layout id) in your activity's onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
}

in your other activities just changue your setContentView id like this :-
old contentViewId:-
setContentView(R.layout.yourCurrentView);
change id:-
setContentView(R.layout.yourNewView);

Related

Android CardView implementation

I created an Android app with list view. Whenever the an element is clicked, it passes intent to cardview.I have a single cardview in my layout file, and use it for every element in the listView.
For each list item, I define different implementation for the CardView in Java passing intents from one java file to the other. .
Please is this a good practice using a single card view and Recycler View for multiple elements changing their text programmatically. I haven't seen anyone do something like that.
Edit
#Ankit something like ...
Something like
>
<android.support.v7.widget.RecyclerView/>
</LinearLayout>```
**Tutorial page 1**
```public class Lesson_Galaxy_One extends AppCompatActivity
{ super.onCreate(savedInstanceState);
setContentView(R.layout.lesson_galaxy);
}```
**Tutorial 2**
```public class Lesson_Galaxy_Two extends AppCompatActivity
{ super.onCreate(savedInstanceState);
setContentView(R.layout.lesson_galaxy);
}```
**Tutorial 3**
```public class Lesson_Galaxy_Three extends AppCompatActivity
{ super.onCreate(savedInstanceState);
setContentView(R.layout.lesson_galaxy);
}```
Each with different elements for the RecyclerView's CardView with intents being passed from one to the other.
There won't be any issues of using a single card view for multiple list items.It's totally fine .

Android Studio "not assignable to android.app.activity" and "no default constructor" errors

enter image description here
enter image description here
enter image description here
Am a complete beginner to Java and AS.
Trying to make a revision app in the form of quizzes. Please let me know what advice you d give for these errors.
tried to add a public default constructor though I guess incorrectly.
I expect to be able to call this class from another one to calculate score and progress for questions
Welcome Angela
Activity is one of main component of Android and Android OS is responsible for instantiation of this components.
But in Action for defining an activity we should extending AppCompatActivity like this :
public class MyActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
}
And DO NOT create a constructor for activities.

Clarification regarding findViewById(int id) method in Android

I am going through Head First Android Development and I am a bit confused with
this method --> findViewById(int id)
I have the below button in the file "activity_find_beer.xml" :
<Button
android:id="#+id/find_beer"
android:text="#string/find_beer"
android:onClick="onClickFindBeer" />
and the following code from the class FindBeerActivity.java which is taking the user selected beer and displaying the same in a textview.
public class FindBeerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_beer);
}
//Call when the button gets clicked
public void onClickFindBeer(View view) {
//Get a reference to the TextView
TextView brands = (TextView) findViewById(R.id.brands);
//Get a reference to the Spinner
Spinner color = (Spinner) findViewById(R.id.color);
//Get the selected item in the Spinner
String beerType = String.valueOf(color.getSelectedItem());
//Display the selected item
brands.setText(beerType);
}
}
My Question is the method onClickFindBeer(View view) takes a View type of
object as a parameter , but in the xml i have just mentioned
android:onClick="onClickFindBeer" and when the user clicks the
button , the method onClickFindBeer gets invoked...Who is passing the object of
type View to the onClickFindBeer(View view) ...is it something
implicit ?
Second,on developer.android.com I see that the method
findViewById(int id) is both in the Activity class (
https://developer.android.com/reference/android/app/Activity.html
) and also in the View class
https://developer.android.com/reference/android/view/View.html
... It's not clear to me which class (Activity or View)
findViewById(int id) method is invoked when i call findViewById()
from onClickFindBeer(View view){}.
Would be highly obliged if someone could throw light on this.
Regards.
The method takes a View parameter as that is how it is implemented in a superclass of the Button class (It is public class Button extends TextView.). The views you add to XML are actually java classes. When you set a property to such an XML item, that constructs the object from the particular java class accordingly. The onClick method of the View class goes as onClick(View v). By setting an XML you just asked the Button class to look for the entered method but its signature is always with a View as a paramenter, which refers to the view clicked.
findViewById has to be called on a View group. But the Actyvity class implements it to search an item in view assigned to it by the setContentView() method.
It is done somewhat implicitly. When building your app, the XML file is actually converted into Java file. When you click the view, the view is passed into the onClickFindBeer(View view) function.
The findViewById() is being called here by the activity. You can see the method declaration by clicking on findViewByID while pressing Ctrl. For a view, you would have to call it using the view. For example,
view.findViewById();
Its called JAVA Reflection which is used by android
2.
As I know, main difference is that when you used OnClickListener from activity it is connected with partivular object such as Textview,Button
find_beer.setOnClickListener and below code is excuted when someButton is pressed.
While android:onClick = "onClickFindBeer" is used handle click directly in the view's activity without need to implement any interface
You have assigned the method onClickBeer to your button. When the button gets clicked, the object, in this case the button, is passed to the method you assigned to it. A Button is a type of View object, so you have a more generic View object as the parameter, but you are perfectly ok to caste it to a button object.
findViewById is called through a "context", which is a way of getting at system resources. You are asking the system to return to you a specific object, which you can then use. It is worth reading up on contexts.
Hope that answers some of your query.
Base on your sample above the android:onClick method is the one being invoked because when invoking a onclick method in java class, it need to call a onClickListener.
cause on the other question. as far as I know it belong to the view class because it always to reference an object on your design.

Is it possible to save Stack<Stack<View>> in onSaveInstanceState

Is it possible to save Stack<Stack<View>> in onSaveInstanceState.
May some another way how to save some specific data to manage Activity state?
You can't save views to bundle. And you shouldn't do it anyway. If activity is recreated it will reinflate layout again (or even inflate another one if configuration has changed) and create a new view hierarchy.
You should separate business data from your UI and store it onSaveInstanceState. After activity recreation you should get that data and update new views hierarchy accordingly.
For example, if you have a TextView, that displays some text that is stored in a field mSuperText, and your activity is going down, you should save it into a bundle in onSaveInstanceState:
#Override
protected void onSaveInstanceState(final Bundle outState) {
outState.putString("supertext", mSuperText);
}
And when your activity is recreated, in your method onCreate you get an argument onCreate(final Bundle savedInstanceState) which will be the bundle you stored previously. So you can get values you need:
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mSuperText = savedInstanceState.getString("superText");
}
}
Is it possible to save Stack> in onSaveInstanceState.
No, because Stack and View doesn't have the Parcelable / Serializable interface, which is necessary to put an Object in a Bundle. A Bundle only takes Arrays/ArrayList, String, primitives and so on.
May some another way how to save some specific data to manage Activity
state?
Which data you wanna save? If you wanna save a whole View/ViewGroup you are probably on the wrong way.
E.g to indicate that a TextView was visible set a boolean to true and put it in the Bundle. Check the boolean in onCreate() and set the View to visible. If the TextView had some text too, save it as String and set the text to the TextView, which you made visible.

ActionBar in PreferenceActivity

In my application I am using the new Action Bar Compatibility sample from Google (located at <sdk>/samples/android-<version>/ActionBarCompat) which works great. The only problem I have is applying this to my PreferenceActivity in order to get a screen like the settings in the Android Market (see picture).
To fill the ActionBar with icons, each Activity must extend the ActionBarActivity class. The problem is that my Activity already extends PreferenceActivity and in Java classes can not extend more than one class.
There must be a way to get the ActionBar together with a PreferenceScreen. I would be glad if anybody could provide a solution for this common issue.
P.S.: A solution like in How to add a button to PreferenceScreen does not fit because the ActionBar is actually the title bar and so this is more a Java than a layout thing.
Edit: My answer below is rather hacky and it seems like it is now outdated (for pre Android 3.0) Have a look at the other answers for less hacky and more current solutions ~pyko 2014-09-01
I managed to get it working - not sure if this is the nicest/cleanest solution, but it works.
Had to make the following changes:
Make a copy of ActionBarActivity and have the new class extend PreferenceActivity
public abstract class ActionBarPreferenceActivity extends PreferenceActivity {
// contents exactly the same as 'ActionBarActivity'
}
Modify onCreate() in ActionBarHelperBase.java slightly - make a special case for PreferenceActivity classes
#Override
public void onCreate(Bundle savedInstanceState) {
// If the activity is a PreferenceActivity, don't make the request
if (!(mActivity instanceof PreferenceActivity)) {
mActivity.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
}
Have your PreferenceActivity extend this class and add request for FEATURE_CUSTOM_TITLE before you call super.onCreate()
public class MyPreferenceActivity extends ActionBarPreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // add this line
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// etc etc
}
// etc etc
}
As far as I can tell, changes 2 and 3 are needed because for PreferenceActivity:
"As soon as you call super.onCreate(), the ViewGroup will be set up and so, you are not allowed to change the Window's parameters." (see Oliver's comment to the answer)
I guess the order of how components in PreferenceActivity activities are created is different to plain Activity activities .
If you want to try a PreferenceFragment implementation based on support-v4 Fragment:
https://github.com/kolavar/android-support-v4-preferencefragment
I´m using it by myself and it isnt much work turning PreferenceActivity into PreferenceFragment.
Can you just clone the code for ActionBarActivity, and change "extends Activity" to "extends PreferenceActivity"? Then extend your new class instead of ActionBarActivity.
From all the Google apps I've seen, though, it seems unusual to put buttons in the action bar of a PreferenceActivity. If you're not putting buttons on it, you could just use a values-v11 alternate style resource to show the holo theme, and set that style in the manifest for your PreferenceActivity.
I used in my application this actionbar
https://github.com/johannilsson/android-actionbar and it's work great with this thread How to add a button to PreferenceScreen
I'd like to thank to #pyko providing a great answer, but it has problem that it won't work well on HoneyComb and above. well you can have a hack way to get it around like #AndroidDev said;
But #pyko is gonna pollute the ActionBarHelperBase class, and #AndroidDev isn't very transparent.The best way is to create ActionBarActivityPreferences who extends from PreferenceActivity; and in onCreate method, change the order of calling parent method:
#Override
protected void onCreate(Bundle savedInstanceState) {
//IMPORTATNT: MAKE SURE actionBarHelper called before super;
//as super oncreate of prefenceactivity is actuallying setting the content view
mActionBarHelper.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
why calls 'mActionBarHelper.onCreate(savedInstanceState);' before 'super.onCreate(savedInstanceState);' , that is because super (i.e. PreferenceActivity) is actually setting the content view in its onCreate method, which would cause crash ("requestFeature() must be called before adding content'). SO what you need do is to swap the order, make sure ' mActionBarHelper.onCreate(savedInstanceState);' is called before super.
In this way, we don't need to pollute the 'ActionBarHelperBase' yet we keep SettingActivity very clean because we encapsulate the tricky detail to 'ActionBarActivityPreferences' and bang!
You can easily add action bar in preference activity by the following changes:
In AndroidManifest.xml :
<activity
android:name=".activity.SettingsActivity"
android:theme="#style/SettingsTheme"
android:label="Settings"/>
In v21/styles.xml
<style name="SettingsTheme" parent="#android:style/Theme.Material.Light.DarkActionBar">
<item name="android:colorPrimary">#color/colorPrimary</item>
<item name="android:colorPrimaryDark">#color/colorPrimaryDark</item>
</style>
In v14/styles.xml for Back API support:
<style name="SettingsTheme" parent="#android:style/Theme.Holo.Light.DarkActionBar">
<item name="android:actionBarStyle">#style/ActionBar.V14.Movie.NoTitle</item>
</style>
Thanks, just an update, you need to add an if statement before the Custom Title line to support HoneyComb and above.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
You can get a ActionBarSherlock lib and let you code extends SherlockPreference;

Categories

Resources