How do I reference an image from another layout? - java

to replace the image in the layout programmatically, in my case, i need to refer to the image from another layout of the other class. There is: the first class, which is extended by the second class, each class has its own layout. I need to refer from the first class to the image in the mockup of the second class.
How do I do this based on the image replacement code below?
ImageView img= (ImageView) findViewById(R.id.image);
img.setImageResource(R.drawable.my_image);

pass some value to 2nd activity before starting using putextra based on the value set image there .
if it is from second to first that use startactivityforresult and setresult

You can use the image anywhere you want
public class Activity2 extends Activity1 {
ImageView changeImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int image1 = R.id.imageView1;
int image2 = R.id.imageView2;
changeImage = (ImageView)findViewById(R.id.imageView1);
changeImage.setImageResource(**you can add your image1/image2 **);
}
}
Think this will solve your problem

NOTE: Parent to child calling is not recommended as it kind of destroys the reason for inheritance. The best way would be to restructure your application design so that there are NO parent to child dependencies. A parent should not ever need to know its children or their capabilities.
However.. you can achieve this by following method in FirstClass :
void udpate(SecondClass s) {
if(s instanceof SecondClass) ((SecondClass)s).updateImageView(String url);
}
where updateImageView would be method inside your SecondClass for updating required imageView.
Hope it helps.

Related

How to pass custom objects from an activity to a fragment?

I've been searching all day and couldn't find a real answer. I created a fragment using the correct way, that is with a no-args constructor and using Fragment setArguments(Bundle) to pass data to it.
I need to pass a Drawable and another custom object to the fragment. Everything I read talks about passing the integer ID of the drawable instead of the drawable object. But the drawable I'm passing doesn't have an ID, it's from an array of drawables that includes all the icons of the user's installed apps, and this array was already loaded beforehand. I just want to pass the drawable without having to recreate anything inside the fragment. Is this possible?
You can do something like this:
Your activity:
public class YourActivity extends AppCompatActivity {
...
public Drawable drawableToGet; //Here is the drawable you want to get
...
}
In your Fragment:
public Drawable getDrawableFromActivity(){
Activity activity = getActivity();
if(activity instanceof YourActivity){
return ((YourActivity) activity).drawableToGet;
} else {
//Fragment isn't attached to YourActivity
return null;
}
}

Activity Instance does not exist- null object reference

I am trying to develop an Android application. For my use case I want to use a custom typeface and I wrote a that gathers all available TextViews in a View, so that I can set the typeface easily by a loop. I thought I should source out the text manipulation things to an own class named TextManager.class . But now when I am executing the app I am getting an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
It occurs when I am trying to set Typeface in TextMangaer.class . I did a bit of research and found out that it is because the activity instance does not exist at this point. But I don't get it why, cause when I am trying to do this in Start.class there is no problem.
//Start.class
public class Start extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // set fullscreen
//Initialize shared preferences
prefs = getSharedPreferences("User", Context.MODE_PRIVATE);
editor=prefs.edit();
setContentView(R.layout.start_screen);
TextManager textManager= new TextManager();
textManager.setTypeface(getTextViews((ViewGroup) findViewById(R.id.root_menu)));
}
}
and my TextManager.class:
public class TextManager extends Start{
public TextManager(){
super();
}
public void setTypeface(List<Integer> idsOfTextViews){
Typeface typeFaceIkarosLight= Typeface.createFromAsset(getAssets(), "font/ikaros_light.otf");
for(int i=0; i < idsOfTextViews.size();i++){
((TextView)findViewById(idsOfTextViews.get(i))).setTypeface(typeFaceIkarosLight);
}
}
}
So how could I fix this or how should I write this? If anybody could help me figure it out that would be great. Thanks in advance.
Problem is context is null for getting assets.
Use getContext() or getApplicationContext() in case of being used in an activity but if it is being used in a fragment then use getActivity().getContext()
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "font/ikaros_light.otf");
Instead of
Typeface typeFaceIkarosLight= Typeface.createFromAsset(getAssets(), "font/ikaros_light.otf");
Its better to make method which return typeface instead passing textview ids as an argument. you can do it like this :
public Typeface getTypeFace(Context context){
Typeface typeFaceIkarosLight = Typeface.createFromAsset(context.getAssets(), "font/ikaros_light.otf");
return typeFaceIkarosLight;
}
If you want to use custom fonts then you can take this example
This tutorial will show you how to set custom font on TextView, EditText and on Button.
http://androiderstack.com/index.php/2017/08/14/use-custom-font-in-textview-edittext-and-button-in-android/
This will surely help you

Changing background in other activities with a button

I have a problem. I have 3 activities (MainActivity, DetailsActivity, SettingsActivity) and in SettingsActivity I have a Togglebutton "Nightmode". What I want is, when the button is changed, change background of all three activities on gray color.
public class SettingsActivity extends AppCompatActivity {
//This is SettingsActivity(not Main one)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
TextView SettingsTitle = (TextView) findViewById(R.id.SettingsTitle);
TextView NightText = (TextView) findViewById(R.id.NightmodeText);
ToggleButton toggleNightMode = (ToggleButton) findViewById(R.id.toggleNightmode);
final RelativeLayout NightBG = (RelativeLayout) findViewById(R.id.NightBG);
final LinearLayout DetailsBG = (LinearLayout) findViewById(R.id.mainBG);
final LinearLayout HomeBG = (LinearLayout) findViewById(R.id.HomeBG);
toggleNightMode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NightBG.setBackgroundColor(Color.parseColor("#545657"));
HomeBG.setBackgroundColor(Color.parseColor("#545657"));
DetailsBG.setBackgroundColor(Color.parseColor("#545657"));
}
});
NightBG is in the same activity as that java file (SettingsActivity). But HomeBG is in MainActivity and DetailsBG is in the DetailsActivity. Everytime I start the app, and press on that button, app craches. If I delete HomeBG and DetailsBG from this file, it works just fine with changing current layout's color to gray. Please help me.
One easy way to store little settings like this across multiple activities that may not be open/active at the time of the button click would be to use SharedPreferences.
It might be a little overkill for such a simple piece of code but you can always give it a try if you don't find anything else.
Your code could look something like this:
toggleNightMode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Set the color of this activity
int color = Color.parseColor("#545657")
View view = SettingsActivity.this.getWindow().getDecorView();
view.setBackgroundColor(color);
// Save color preference
SharedPreferences sharedPref = SettingsActivity.this.getSharedPreferences("bgColorFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("color", color);
editor.apply();
}
});
And then when you open your activities you place something like this in the onStart() or onCreate() method of your activity:
// Get the color preference
SharedPreferences sharedPref = getSharedPreferences("bgColorFile",Context.MODE_PRIVATE);
int colorValue = sharedPref.getInt("color", 0);
View view = this.getWindow().getDecorView();
view.setBackgroundColor(colorValue);
So what you're actually doing is storing the background color as persistent data and fetching it once you reopen/open the activity that you want to have the color on. The benefit of this method is that whenever you close your app the preferred background color will be remembered. I hope this helps.
Change background for current activity in the same activity. Since DetailsActivity is not running, you can't do that, it gives you null pointer. Is kind of you are trying to eat 3 apples and you have just one. After current activity is started, change background.
Update:
You can do that in current activity and just in current activity:
findViewById(android.R.id.content).setBackground(getColor(R.color.your_color));
Don't try to call this in other activities that are not running.
setBackground()
or
setBackgroundColor()
If your other activities are open, you should send a message to the other activities by using an Intent.
How to send string from one activity to another?
When you receive the Intent you could then set the background of the activity.
If your other activities are not open yet, you will not be able to send an Intent to them. In this case you could have each Activity reference a static value in your main activity that could contain the current background color. You would want to reference that value on the other activities on create functions.
Here is an example on how to reference a variable from another activity.
How do I get a variable in another activity?
This might not be the most pretty way to handle it but it should work.
as Ay Rue said you have 2 options: use static variable for that button, and then in onResume of each activity, check the value of the static variable (true or false). or you can save a private variable nightMode and then pass this value in the intent when you need to move to the other two activities.
don't set the background color if you already set before and have an updated background color.

when am I safe to query a View's dimensions?

I'm trying to grab the dimensions of a view in my activity. The view is a simple custom view which extends an ImageView:
<com.example.dragdropshapes.CustomStrechView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/border"
android:src="#drawable/missingpuz"
android:clickable="true"
android:onClick="pickShapes"
/>
I need to know what the specific "fill_parent" ends up being. I attempted to get this information during the onCreate method of the Activity using the layout containing my custom views:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_puzzle_picker);
// Show the Up button in the action bar.
setupActionBar();
int a = findViewById(R.id.pickshapes).getMeasuredHeight();
int b = findViewById(R.id.pickshapes).getHeight();
In this case, both a and b return a value of 0. Later, the custom view will be used as a button (it has an onClick handler) so I thought to try again to get the size in the handler:
public void pickShapes(View view){
Intent intent = new Intent(this, ShapesActivity.class);
int a = findViewById(R.id.pickshapes).getMeasuredHeight();
int b = findViewById(R.id.pickshapes).getHeight();
startActivity(intent);
}
Here a and b both give valid dimensions... I don't want to wait for a "onClick" event however, I want to get the dimensions as soon as possible. I've tried Overriding both onStart() and onResume() to check the dimensions as well, but in both cases I still get 0.
So my question is, where in the Android Activity start up flow, is the first place I can get the actual size of a View? I want to be able to get the height/width as soon as I can, and I want to do it before the user has a chance to interact with the environment.
There's a fairly useful thing in Android called the ViewTreeObserver. I've done precisely what you need to do many times this way. As you've discovered, you need to wait until at least the measure cycle completes. Try something like the following:
...
setContextView(R.layout.activity_puzzle_picker);
final View view = findViewById(R.id.pickshapes);
view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int height = view.getMeasuredHeight();
if(height > 0) {
// do whatever you want with the measured height.
setMyViewHeight(height);
// ... and ALWAYS remove the listener when you're done.
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
}
});
...
(Note that you haven't set the id of your view in your XML... I'm using R.id.pickshapes because that's what you chose.)

TextView setText from another class

My problem is that i've a tabhost with two tabs.
The first is a listview and the second only have two textviews.
What i want is when i click on an item in the listview on tab one, the array position id (int) should be sent to tab/class two, where there is an array who fetches a text by the position id that was sent.
The switching of tabs is done, but i fail everytime i try to send the position-id.
This is how i send it:
TAB ONE:
//This function is called when i click a listitem
public void setDetails(String Text, long arr_id){
Detail detail = new Detail();
detail.setDetail(); // right now i don't send the parameters because it wont even work with or without it.
}
TAB TWO:
TextView descr;
TextView title;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
descr = (TextView)findViewById(R.id.desc);
title = (TextView)findViewById(R.id.title);
}
public void setDetailText(String Text){
descr.setText(Text);
}
public void setDetailTitle(String Text){
title.setText(Text);
}
public void setDetail(){
this.setDetailTitle("example text");
this.setDetailText("example text2");
}
I want to set the text on tab two BEFORE it switch to tab two.
This works if i use SetDetail() and setDetailTitle() in the same tab/class, but not in another.
I've googled my ass off, please help me
i do this in my code using getParent() or getActivity() methods in my TabActivity and inner Activitys, cause if we use a TabActivity (wich subclass the ActivityGroup class) we can obtain the 'TextActivity' using ActivityManager and obtain the activity instance, so, here we can call the setDetail() method, and this will execute before the Activity is showed,
in your ListActivity do something like this
((MyTextActivity)((MyTabActivity)getParent()).getLocalActivityManager().getActivity(ACTIVITY_ID)).setDetail();
this works only if in you start the childs activity within your TabActivity with:
intent = new Intent(ACTIVITY_ID).setClass(this, MyMapActivity.class);
getLocalActivityManager().startActivity(ACTIVITY_ID, intent);

Categories