Don't understand the constructor of my View - java

My code is working and so, but I don't understand one thing.
I've started game programming and now works my whole SurfaceView and so on. I have draw a background so it all works.
When I created this I followed a tutorial, so know I'm commenting on my own language. :)
When I now started to comment some things; I can't get rid of this, can someone tell me why my constructor for my view has the Context parameter and AttributeSet paramater? What makes it necessary to have these and why do I need to set the localContext value to my GameView context?
Game
public class Game extends Activity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(new GameView(this, null));
}
}
GameView
public GameView(Context localContext, AttributeSet attrSet){
super(localContext, attrSet);
context=localContext;
InitView();
}
The InitView(); just initialize every objects and variables I created; if this stuff is needed in order to explain the constructor-thing to me; I will post it.
Thanks!

The Context carries a bunch of state with it that Views use to operate. This includes things like configuration state to help the resource system determine which resources to use among a number of others.
The AttributeSet is used when your view is inflated from an XML layout. This is how XML attributes get bound to view properties during layout inflation.

Related

can I use static layout (native UI) in react native's native android implementation?

I am writing a react native application and I want to use some of the static layouts (for Android) I have from my old application.
I looked at https://facebook.github.io/react-native/docs/native-components-ios.html and wrote a few classes (MyViewManager.java and MyView.java).
I want to be able to use the static layouts I have for MyView.java.
I went through the facebook's react native code on github.
I could not find an appropriate method like setContentView(R.layout.myview). I was wondering if anybody tried this and this will work.
Can someone please help me with this problem?
You can try out something like
The layout inflater will inflate given xml file and put it as a child of this(second argument in inflate), which is MyLayoutView.
See the definition of inflate and change arguments as per customization required.
public class MyManyViewsManager extends ViewGroupManager<MyLayoutView> {
}
class MyLayoutView extends FrameLayout {
init() {
rootItem = (ViewGroup) LayoutInflater.from(getContext()).inflate(R.layout.xmlfilename, this, true);
}
}

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.

Static Context from Activity.onStart()

I am trying to generate a notification from a class, Utilities.java, outside of the subclass of Context. I've thought about providing a SingletonContext class and have looked at posts ike this. I'd like to be able to return != null Context object since the notification can be generated at any given time because it is generated from a messageReceived() callback.
What are there downsides to doing something like this:
public static Context c;
public class MainActivity extends Activity{
#Override
public void onStart()
super.onStart()
c = this.getApplicationContext();
}
//other method somewhere outside this class
public Context getContext(){
return MainActivity.c
}
I don't think it would be any different than putting this on the onCreate(), however, it guarantees that the context is up to date when the activity starts.
The Context keeps a reference to this activity in memory, which you might not want. Perhaps use
this.getApplicationContext();
instead. This will still let you do file IO and most other things a context requires. Without a specific reference to this activity.
Maybe you should overwrite the onResume Method.
If you open a new activity, and switch back, the onStart method will not getting invoked.
Android Lifecycle: doc
BTW: I read about problems with ApplicationContext using a dialog or toast, so if you use the context to create on of these you should use your Activity as context.

Context having reference to class in android

Hi i am trying to understand the use of context though i couldn't. Following is a program using context. My question is what is the significance of " context = class.this " ?
class public VcardActivity extends Activity
{
String Vcard = "vcard";
Context context;
}
public void onCreate ( Bundle bn )
{
super.onCreate(bn);
setContentView(R.layout.main);
context = VcardActivity.this;
}
Your current code doesn't show the use of context. It shows that the Activity is a context.
TextView someText=new TextView(context);
This code of mine shows, I am passing a context into the constructor of a TextView in order to make this object. The reason is, this object needs to know the information, state of the current context, and this is the reason why many views, classes, helpers needs a context.
context = VcardActivity.this;
in your code you are having your activity object to assign to the Context context. This works because Activity class inherits from Context and many classes needs a Context to create it.
In your case, the field context is not necessary at all. It rather is used as a shortcut to VcardActivity.this here. You could remove it without any problems and use VcardActivity.this or even only this where you used to use context.
You don't need to create a separate Context variable inside of an Activity. You use Context for certain objects/methods that need to know what is starting them. Activity already has a Context so you don't need to create it. If you need to use Context within an Activity, say when creating an Intent you can just use ActivityName.this or here VcardActivity
See this SO answer for a good explanation of using which kind of Context when.
Context Docs

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