how to set background of activity by user choice in android studio - java

RelativeLayout layout = (RelativeLayout) findViewById(R.id.relativer);
layout.setBackgroundResource(R.drawable.bgorange);
I want the bgorange to get retrieved from a spinner. So bgorange is a static value for now.

In general, for getting a resource programmatically you can use:
public static final Drawable getDrawable(Context context, int id) {
return ContextCompat.getDrawable(context, id);
}
So, in your exmaple you can use it like this:
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relativer);
Drawable drawable = getDrawable(context, YourSpinner.getYourResBackground());
layout.setBackgroundDrawable(drawable)
Note that you need the latest support lib in your build.grade
compile 'com.android.support:support-v4:xxxxxx

Related

Android: How to add a layer on top no matter how many activities started?

I want to play a gif animation and this view will move on the screen every second, but if I start an activity I need to add this view again and the position will change.
See the attached image below. I need to stick this over every view. Any way to do it?
Create one BaseActivity for all activities in your app to show Overlay View or Layout.
you can inherit BaseActivity on other Activity
You can add gif supported views or layouts
for example i added overlay_layout in my showOverlay method.
you can call showOverlay method where ever you want to show and you can remove with removeOverlay with conditions.
Please note that showOverlay and removeOverlay should be in BaseActivity
void showOverlay(){
LayoutInflater inflater = activity.getLayoutInflater();
layout = inflater.inflate(R.layout.overlay_layout, null);
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.gravity = Gravity.BOTTOM;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.type = WindowManager.LayoutParams.TYPE_APPLICATION;
final WindowManager mWindowManager = (WindowManager);
activity.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
mWindowManager.addView(layout, params);
}
void removeOverlay(){
windowManager.removeView(view);
}
set this view into WindowManager and it will always show on top

Android Set ImageView Source from Java

I want to set an Image Source in Android,
XML :
<ImageView
android:layout_width="200dp"
android:layout_height="300dp"
android:id="#+id/main"
android:src="#drawable/malayali"
android:layout_marginTop="100dp"
android:layout_marginLeft="80dp"
/>
Java :
public class MainActivity extends ActionBarActivity {
public SharedPreferences exactPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
exactPreferences = getSharedPreferences("details",MODE_PRIVATE);
getSupportActionBar().hide();
new RetriveIcon().execute(); //Api Calling & Storing value in SharedPreference
String value = exactPreferences.getString("main_url",null);
Log.i("from exactpreference",value); // Working fine !!! (http://www.exampple.com/storage/images/filename.jpeg)
ImageView banner = (ImageView)findViewById(R.id.main);
banner.setImageDrawable(getResources().getDrawable(R.drawable.value));
setContentView(R.layout.activity_main);
}
}
androidStudio showing error in the below line of value as red.
banner.setImageDrawable(getResources().getDrawable(R.drawable.value));
ERROR:
Cannot resolve symbol 'value'
How can I solve this Error ?
If you are dealing with the drawable name in your Resources folder, then Your problem is one of those options:-
1)You don't have the drawable value in your Resources.
Make sure it exists in your resources folder.
2)You are importing the wrong R in your activity
Make sure you are importing your application R not the android one.
If your are using a Direct URL for the image. I recommend you to use Universal Lazy Loader third party for that. All you have to do is to pass the image direct URL and the ImageView and it will do the job for you.
In your Gradle file "Module:app"
dependencies {
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'
....
}
Are you trying to load an image from your drawable folder or download one from the Internet?
This:
banner.setImageDrawable(getResources().getDrawable(R.drawable.value));
Will work if you have a value.png file in one of your drawable folders. If you are trying to load an image from the net (i.e. something like this: http://www.exampple.com/storage/images/filename.jpeg), you'll need to download it first and set the bitmap as an ImageView source. There are many 3rd party libraries doing this. Take a look at Picasso:
Picasso.with(this).load(value).into(banner);
EDIT:
In order to add Picasso you need to update the build.gradle file (the one which refers to a module not project). You should have a section like this:
dependencies {
...
}
You need to add this line inside it:
compile 'com.squareup.picasso:picasso:2.5.2'
Try this Simple code
ImageView banner = (ImageView)findViewById(R.id.main);
banner.setBackgroundResource(R.drawable.value);
But image name must be value and store in your drawable folder.
Try this :
String uri = "#drawable/myresource.png";
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
Drawable res = getResources().getDrawable(imageResource);
imageView.setImageDrawable(res);
Note : This is sample code.
You want to set your imageview's background with an online image file. You can use this example on your project. Usage of this is very easy.
Also in your codes, you should change some lines after adding classes from the above link:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
exactPreferences = getSharedPreferences("details",MODE_PRIVATE);
getSupportActionBar().hide();
new RetriveIcon().execute(); //Api Calling & Storing value in SharedPreference
String value = exactPreferences.getString("main_url",null);
Log.i("from exactpreference",value); // Working fine !!! (http://www.exampple.com/storage/images/filename.jpeg)
// ImageLoader class instance
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
ImageView banner = (ImageView)findViewById(R.id.main);
imgLoader.DisplayImage(value, 0, banner);
}
Good luck.

Click listview item and display image

im trying to create a listview where if you press an item on that list, it displays an image in fullscreen. I have about 10 different items in the list and I want to display different images for each item.
I used this tutorial: http://www.androidhive.info/2011/10/android-listview-tutorial/
But instead of showing the name of my string item, i want it to show an image. How do i fix this?
I have been trying to check other questions, but they have been kinda hard to follow since im new to this.
First of all you need to have images in your drawable folder for all different items(in list view)
Change the single_list_item.xml to
single_list_item_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
change your SingleListItem.java
package com.androidhive.androidlistview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
ImageView productimage = (ImageView) findViewById(R.id.image);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
switch(product){
case "item1":
productimage.setImageDrawable(R.drawable.image1);
break;
case "item2":
productimage.setImageDrawable(R.drawable.image2);
break;
case "item3":
productimage.setImageDrawable(R.drawable.image3);
break;
.
.
.
.
.
//upto all 10 images
}
}
}
You should be able to do this with only a few changes to the tutorial code.
First, in single_list_item_view.xml, you'll need to use an ImageView instead of a TextView, since you want to show an image. You can find documentation for image views, including what attributes they support, on the Android developer site.
Second, you'll need to change the line that looks up the TextView to find your new ImageView instead. This will only require changing the following line:
TextView txtProduct = (TextView) findViewById(R.id.product_label);
to:
// Assuming you gave your ImageView the id "product_image" in single_list_item_view.xml
ImageView productImage = (ImageView) findViewById(R.id.product_image);
You'll need to add the images that you want to show into your project. The simplest place for these to go is in the res/drawable folder. The name of the image files will determine their "ids". For example, if you have res/drawable/photoshop.png, you can refer to it with the id R.drawable.photoshop.
Next you need to figure out which image to show in SingleListItem. The key part of how clicking on an item in the list shows something else is in SingleListItem:
Intent i = getIntent();
String product = i.getStringExtra("product");
Correspondingly, in AndroidListViewActivity:
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
i.putExtra("product", product);
startActivity(i);
The Intent is how you send information from the list activity to the activity that shows the item. In this case, the information being sent is which item to show. You have a few options about how to do this part. One simple way is just to inspect the product string and choose the appropriate drawable:
int imageId = -1;
if (product.equals("Adobe After Effects")) {
imageId = R.drawable.after_effects;
} else if (product.equals("Adobe Bridge")) {
imageId = R.drawable.bridge;
} else if ...
... // All your other cases
}
This approach obviously doesn't scale very well, but it will work okay for your simple example. Another possible approach would be to pass the image id in the Intent, rather than the product name, for example:
// In AndroidListViewActivity:
i.putExtra("product", R.drawable.after_effects);
// In SingleListItem:
int imageId = i.getIntExtra("product", -1);
// -1 in the call above is the value to return if "product" is not in the Intent
The final thing you need to do is set the Drawable for the ImageView you found earlier:
// Make sure to check that the id is valid before using it
if (imageId != -1) {
Drawable d = getResources().getDrawable(imageId);
productImage.setDrawable(d);
}
getResources() fetches the Resources object for you application. You can use the Resources object to look up things like strings and drawables you've defined in your res folder. The tutorial you're following also uses it to look up an array of strings in the res folder. Again, you can see everything Resources supports on the Android developer site.
Instead of showing the item/text in SingleListItem class you could use the passed item to check which image should be displayed in an imageview. Something like that:
public class SingleListItem extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
// TextView txtProduct = (TextView) findViewById(R.id.product_label);
ImageView image = (ImageView) findViewById(R.id.someImage);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
if (product.equals("item1")) {
image.setDrawableResource(R.drawable.YOURIMAGE);
} else if (product.equals("item2"))
image.setDrawableResource(R.drawable.ANOTHERIMAGE);
}
}

Change font of all list items in a list view

I have set up a working custom list view array adapter code is almost similar to the one showed here (without the cache part)
now how do I change the font of all the items to something like roboto
edit
i tried this
added private Typeface textFont; before oncreate();
TextView yourTextView = (TextView) listAdapter.getView(0, null, null);
TypefacetextFont=Typeface.createFromAsset(getApplicationContext().getAssets(),"RobotoBoldCondensed.ttf");
yourTextView.setTypeface(textFont);
Create a folder in the root of your project called assets/fonts/ then paste the TTF font file (in this case roboto.ttf).
Then use that from your adapter's getview() method like this:
#Override
public View getView ( int position, View convertView, ViewGroup parent ) {
/* create a new view of my layout and inflate it in the row */
convertView = ( RelativeLayout ) inflater.inflate( resource, null );
/* Extract the city's object to show */
City city = getItem( position );
/* Take the TextView from layout and set the city's name */
TextView txtName = (TextView) convertView.findViewById(R.id.cityName);
txtName.setText(city.getName());
/* Take the TextView from layout and set the city's wiki link */
TextView txtWiki = (TextView) convertView.findViewById(R.id.cityLinkWiki);
txtWiki.setText(city.getUrlWiki());
Typeface face=Typeface.createFromAsset(getAssets(),"fonts/roboto.ttf");
txtName.setTypeface(face);
txtWiki.setTypeface(face);
return convertView;
}
EDIT :
Change this line,
TypefacetextFont=Typeface.createFromAsset(getApplicationContext().getAssets(),"RobotoBoldCondensed.ttf");
with,
textFont=Typeface.createFromAsset(getApplicationContext().getAssets(),"RobotoBoldCondensed.ttf");
in xml:
android:typeface
or in java:
setTypeface
Using Typeface you can change the font of your text, keep desire font ttf file in your assets folder, access and set to your desire view, just like below:
TextView txt = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "roboto.ttf");
txt.setTypeface(font);
For more help check Quick Tip: Customize Android Fonts
Copy your font in to your assest folder and put this code inside of your custom array adapter
TextView yourTextView = (TextView)findViewById(R.id.yourid);
Typeface textFont = Typeface.createFromAsset(context.getAssets(),"YourFont.ttf");
yourTextView.setTypeface(textFont);
It should work.
EDIT
private Typeface textFont;
Declare
#Override
public void onCreate(){
textFont = Typeface.createFromAsset(context.getAssets(),"YourFont.ttf"); }
in OnCreate() or OnStart()
and just use your custom font in your getView()
yourTextView.setTypeface(textFont);

Updating Android Tab Icons

I have an activity that has a TabHost containing a set of TabSpecs each with a listview containing the items to be displayed by the tab. When each TabSpec is created, I set an icon to be displayed in the tab header.
The TabSpecs are created in this way within a setupTabs() method which loops to create the appropriate number of tabs:
TabSpec ts = mTabs.newTabSpec("tab");
ts.setIndicator("TabTitle", iconResource);
ts.setContent(new TabHost.TabContentFactory(
{
public View createTabContent(String tag)
{
...
}
});
mTabs.addTab(ts);
There are a couple of instances where I want to be able to change the icon which is displayed in each tab during the execution of my program. Currently, I am deleting all the tabs, and calling the above code again to re-create them.
mTabs.getTabWidget().removeAllViews();
mTabs.clearAllTabs(true);
setupTabs();
Is there a way to replace the icon that is being displayed without deleting and re-creating all of the tabs?
The short answer is, you're not missing anything. The Android SDK doesn't provide a direct method to change the indicator of a TabHost after it's been created. The TabSpec is only used to build the tab, so changing the TabSpec after the fact will have no effect.
I think there's a workaround, though. Call mTabs.getTabWidget() to get a TabWidget object. This is just a subclass of ViewGroup, so you can call getChildCount() and getChildAt() to access individual tabs within the TabWidget. Each of these tabs is also a View, and in the case of a tab with a graphical indicator and a text label, it's almost certainly some other ViewGroup (maybe a LinearLayout, but it doesn't matter) that contains an ImageView and a TextView. So with a little fiddling with the debugger or Log.i, you should be able to figure out a recipe to get the ImageView and change it directly.
The downside is that if you're not careful, the exact layout of the controls within a tab could change and your app could break. Your initial solution is perhaps more robust, but then again it might lead to other unwanted side effects like flicker or focus problems.
Just to confirm dominics answer, here's his solution in code (that actually works):
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
if (TAB_MAP.equals(tabId)) {
ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_black));
iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_white));
} else if (TAB_LIST.equals(tabId)) {
ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_white));
iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_black));
}
}
});
Of course it's not polished at all and using those direct indices in getChildAt() is not nice at all...
See my post with code example regarding Customized Android Tabs.
Thanks
Spct
This is what I did and it works for me. I created this function in the activity that extends from TabBarActivity
public void updateTab(int stringID) {
ViewGroup identifyView = (ViewGroup)getTabWidget().getChildAt(0);
TextView v = (TextView)identifyView.getChildAt(identifyView.getChildCount() - 1);
v.setText(stringID);
}
You can modify this function to change the image instead of text or you can change both, also you can modify this to get any tab child. I was particularly interested in modifying the text of the first tab at runtime.
I called this function from the relevant activity using this call
getParent().updateTab(R.string.tab_bar_analyze);
Try This:
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
if (TAB_MAP.equals(tabId)) {
ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_black));
iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_white));
} else if (TAB_LIST.equals(tabId)) {
ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_white));
iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);
iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_black));
}
}
});

Categories

Resources