Dynamic set image path - android

In my project, there are a number of images having back and forward images and all images having a common layout. On clicking back and next buttons new images should be displayed.
private int imageCounter = 0;
private ImageView imageView;
private int[] imageArray = {R.drawable.image_w_lbl_0, R.drawable.image_w_lbl_1,};
private int index_count = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.frame0);//this one is the common parent layout for all imageviews
super.onCreate(savedInstanceState);
imageView = new ImageView(this);
ImageButton next = (ImageButton) findViewById(R.id.next);
ImageButton back = (ImageButton) findViewById(R.id.back);
next.setOnClickListener(this);
back.setOnClickListener(this);
//show the default image
this.loadImage(imageArray[0]);
}
#Override
public void onClick(View v)
{
int imagePath = 0;
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.next:
if(imageCounter < 25)
{
imagePath = imageArray[index_count];
}
imageCounter++;
break;
case R.id.back:
if(imageCounter > 0)
{
//imagePath =
}
imageCounter--;
break;
}
this.loadImage(imagePath);
}
private void loadImage(int imagePath)
{
imageView.setImageResource(imagePath);
}
I am able to see my layout only in the output having back and forward buttons with the black background not an image from my drawable folder.
XML Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<ImageButton android:id="#+id/back" android:src="#drawable/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"/>
<ImageButton
android:id="#+id/next"
android:src="#drawable/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right" />
</LinearLayout>

int array of images from resources (i.e. res/drawable-mdpi):
Integer[] imageArray = { "R.drawable.img1", "R.drawable.img2" }
...
imageView.setImageResource(imageArray[0]); // displays img1

Not very clear what you are asking, but do you want to do something like this:
imagePath=R.drawable.image_wo_lbl_0;
You can store image path in this way, if you actually want to do this.

imageView.setImageResource(R.drawable.img1)

Easiest way - Can be consider the below code
We can take advantage of Imageview setImageResource , refer below code for the same.
put image in the drawable like the below order
image_1.png, image_2.png, etc.
int imagePosition = 1;
int resId = getResources().getIdentifier("image_" + imagePosition, "drawable", getPackageName());
imageview.setImageResource(resId);

Use ContextCompat to get drawable(Image in your case). This is one of the new ways to set image to your image view.
imageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.your_image));
You can use ContextCompat to get colors as well.
I use it in my apps and it works properly.

Related

Setimage from the source of an item

I have a code with lots of imageview and I would like to dynamically change them on a click.
Do I really have to create a condition for every imageview clicked or can I do it simpler?
As an example, is there a way to do something like:
#override
public void onClick(View view) {
view.setImageBitmap(null)
}
You can do this if you haven't yet, give onClick for all the images that you put
<ImageView
android:id="#+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/image_1"
android:onClick="onClick"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
/>
Then in the activity you can make the Activity implement View.OnClickListener() and then define its onClick method as
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.image1:
//Do your thing
break;
case R.id.image2:
//Do your thing
break;
//Add all cases like this
}
}
Let me know if this was helpful to you.
In fact, I found a quite simple way to awnser my problem.
first, I put all imageviews in an array and get the id of these in another array.
Then I use Arrays.asList(array).indexOf(view.getId());
Pic[0] = (ImageView) findViewById(R.id.imageView1);
Pic[1] = (ImageView) findViewById(R.id.imageView2);
Pic[2] = (ImageView) findViewById(R.id.imageView3);
...
for (int i = 0; i < Pic.length; i++){
id[i] = Pic[i].getId()
}
int u = Array.asList(id).indexOf(view.getId())
Pic[u].Setimagebitmap(null)

How do I change a button with onclick in android?

I have this button that should change its appearance when I click the button from
state1 to state2 and vice versa.
the heart is 2 different drawables (#drawable/ic_fav_dish_color & #drawable/ic_fav_dish_grey) and the text is 2 different strings (#string/dish_faved & #string/dish_not_faved)
I made the button in xml with that code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/fav_dish_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_fav_dish_color"
android:gravity="start|center_vertical"
android:text="#string/dish_faved"
android:textAlignment="center"
android:layout_margin="8dp"/>
</LinearLayout>
you can use this , you should have two images one that is fill and other is
not
final Button btn = (Button)(findViewById(R.id.fav_dish_button));
final Drawable drawable = getResources().getDrawable(R.drawable.your_fill_heart_image_name);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);
}
});
You should make a click listener on your button like below:
Button mButton=(Button)findViewById(R.id.fav_dish_button);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mButton.setText(getResources().getString(R.string.dish_not_faved););
mButton.setBackgroundResource(R.drawable.ic_fav_dish_grey);
}
});
Update:
Try below code if you want to change drawable left:
// Left, top, right, bottom drawables
Drawable[] drawables = mButton.getCompoundDrawables();
// get left drawable.
Drawable leftCompoundDrawable = drawables[0];
// get desired drawable.
Drawable img = getContext().getResources().getDrawable(R.drawable.ic_fav_dish_grey);
// set image size (don't change the size values)
img.setBounds(leftCompoundDrawable.getBounds());
// set new drawable
mButton.setCompoundDrawables(img, null, null, null);

Making ImageView visible and invisibile

My Xml file:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/pagefw">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="51dp"
android:layout_marginTop="140dp"
android:src="#drawable/cross" />
</RelativeLayout>
My activity class:-
int turn=1;
iv1 = (ImageView)findViewById(R.id.imageView1);
//iv1.setVisibility(View.INVISIBLE);
//iv1.setImageAlpha(0);
iv1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"Image View 1 selected", Toast.LENGTH_SHORT).show();
if(turn%2!=0)
{iv1.setVisibility(View.INVISIBLE);}
else
{iv1.setVisibility(View.VISIBLE);}
turn++;
}
});
What I Did:-
I added an ImageView in the activity having an image, which has onClickListener assigned to it.
What I Want:-
To my image set in the imageview to completely become invisible and visible after each click, i.e. after first click it becomes invisbile and after another click visible and so on.
What I Get:-
After first becoming invisible the image never becomes visible nor am I getting the toast when I click the invisible imageView. I also tried doing it with iv1.setAlpha(); method but also with no result.
Try something like this , using this u'll not need any extra variable
if(iv1.getVisibility()==View.INVISIBLE){
iv1.setVisibility(View.VISIBLE);
}else{
iv1.setVisibility(View.INVISIBLE);
}
Edit:
I have tried and worked using a Button or removing background.
You are applying click on same ImageView, thats the reason why not working for u.You should apply onClick on a diff button. If want on same ImageView than u have to remove Background instead making it invisible.as ex, u have several method to remove bg/src which u can use.one of them
iv1.setBackgroundResource(null);
Edit-2
Ur imageview must have a min height and width as after removing bg ,imageview clicking area is very small.
<ImageView
android:id="#+id/iv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_launcher"
android:minHeight="48dp"
android:minWidth="48dp"
android:onClick="onClick" />
and a boolean for handle image during onClick
boolean avail=false;
and onClick code.
if (avail) {
iv1.setBackgroundResource(0);
avail = false;
} else {
iv1.setBackgroundResource(R.drawable.ic_launcher);
avail = true;
}
Make it more simple by using one boolean paramater that hold the button state, either pressed or not as following:
static final boolean isPressed= false;
iv1 = (ImageView)findViewById(R.id.imageView1);
iv1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"Image View 1 selected", Toast.LENGTH_SHORT).show();
if(!isPressed){
isPressed= true;
iv1.setVisibility(View.INVISIBLE);
} else {
isPressed= false;
iv1.setVisibility(View.VISIBLE);
}
}
});
Set the tag on the image. Set tag 1 or 0 and check the tag to change the visibility of the image.
if(v.getTag()==0)
{
iv1.setVisibility(View.INVISIBLE);
v.setTag() == 1;
}
else
{
iv1.setVisibility(View.VISIBLE);
v.setTag() == 0;
}
I suggest you do it this way:
in your xml you provide the actual width and height of a drawable and do not provide source:
<ImageView
android:id="#+id/imageView1"
android:layout_width="_some_value_"
android:layout_height="_some_value_"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="51dp"
android:layout_marginTop="140dp">
</ImageView>
That is for your view not to become of a size 0*0 when you set your background to something like null or transparent or whatever.
Then, in your activity:
protected void onCreate(Bundle savedInstanceState) {
.....
iv1.setBackgroundResource(R.drawable.cross);
...
}
And onClick():
public void onClick(View v)
{
Toast.makeText(getApplicationContext(),
"Image View 1 selected", Toast.LENGTH_SHORT).show();
if(turn%2!=0)
{iv1.setBackgroundResource(Color.TRANSPARENT);}
else
{iv1.setBackgroundResource(R.drawable.cross);}
turn++;
}
Pretty sure you can simply it like this too:
iv1.setVisibility(!iv1.getVisibility());
Know what I mean?
if(iv1.getVisibility()==View.INVISIBLE){
iv1.setVisibility(View.VISIBLE);
}else{
iv1.setVisibility(View.INVISIBLE);
}

One activitiy with different backgrounds in android

I am trying to create an android app. I have two buttons next and back in my android app. I want when i click on next button its open same activity with different background. Next time i again click next new background image. And on press on back button its show previous image. And if no previous image its shows menu on press. Similarly if background with last image its hide next button. I have no idea how to do this.
I have tried this:
#Override
public void onCreate(Bundle savedInstanceState)
{
onCreate(savedInstanceState);
back = (Button) findViewById(R.id.back);
next = (Button) findViewById(R.id.next);
back.setOnClickListener(this);
next.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.back)
{
startActivty(new Intent(this,));
}
else if(v.getId()==R.id.next)
{
startActivity(newIntent(this,));
}
}
Xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/back">
<Button
android:id="#+id/back"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="25dp"
android:background="#drawable/ques"
android:text="Back" />
<Button
android:id="#+id/next"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/back2"
android:layout_alignBottom="#+id/back2"
android:layout_alignParentRight="true"
android:background="#drawable/ques"
android:text="Next" />
</RelativeLayout>
In layout as you can see i am using image back for background. I want when i click next new background image then next and so on.
But i dont know how to start same activity with differene backgroud.
Don't start new Activity just change the background:
Keep an array of background resources in your activity like:
int[] backgroundResId;
and one int variable to store current background index:
int currentIndex=0;
now inside your onCreate initialize this array with resource id's of all the backgrounds drawables:
backgroundResId=new int[]{R.drawable.a,R.drawable.b,R.drawable.c};
changeBackground()
create function changeBackground in activity:
private void changeBackground(){
findViewById(R.id.root_layout).setBackgroundResource(backgroundResId[currentIndex]);
}
Now onClick of next button increase currentIndex:
currentIndex++;
if(current<=backgroundResId.length){
changeBackground();
}else{
// setVisibility of next button to invisible
}
onBackButton Click
currentIndex--;
if(current>=0){
changeBackground();
//// setVisibility of next button to visible
}else{
//show menu
}
Make an images array and post your data to the next activity:
Intent intent = getIntent();
intent.putExtra("background", imageIdInTheImageArray);
startActivity(intent);
//finish();
and in your onCreate function :
Bundle b = getIntent().getExtras();
if (b != null) {
int background = b.getInt("background");
//set your background
}
You can add an ImageView in your xml file.
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
you can change background using this
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setBackgroundResource(resId);
Try this..
Global:
int[] backgrounds = new int[]{ images in drawable as int array };
int count = 0;
Button back,next;
RelativeLayout img_backn_lay;
JAVA:
setContentView(R.layout.activity_main);
back = (Button) findViewById(R.id.back);
next = (Button) findViewById(R.id.next);
back.setOnClickListener(this);
next.setOnClickListener(this);
img_backn_lay = (RelativeLayout) findViewById(R.id.main_lay);
img_backn_lay.setBackgroundResource(backgrounds[count]);
count += 1;
ClickListener:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.next)
{
if(backgrounds.length != count){
img_backn_lay.setBackgroundResource(backgrounds[count]);
count += 1;
}else{
Toast.makeText(MainActivity.this, "No images", Toast.LENGTH_LONG).show();
}
}
else if(v.getId()==R.id.back)
{
if(count != 0){
img_backn_lay.setBackgroundResource(backgrounds[count]);
count -= 1;
}else{
Toast.makeText(MainActivity.this, "No images", Toast.LENGTH_LONG).show();
}
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_lay"
android:layout_width="match_parent"
android:layout_height="match_parent" >

How to scroll a HorizontalScrollView on button click in android?

I have horizontal scrollview in my android app with Next and Previous buttons.I want to show the these buttons only when the scollview needs scrolling.ie,width of scrollview content exceeds display width.Also want to hide previous and Next buttons when reaching first and last items respectively.How to to next/previous items when click on these buttons?
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff" >
<Button
android:id="#+id/btnPrevoius"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Previous"
android:visibility="gone" />
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:layout_toLeftOf="#+id/btnNext"
android:layout_toRightOf="#+id/btnPrevoius"
android:fillViewport="true" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Next"
android:visibility="gone" />
</RelativeLayout>
activity
public class SampleActivity extends Activity {
private static LinearLayout linearLayout;
private static HorizontalScrollView horizontalScrollView;
private static Button btnPrevious;
private static Button btnNext;
private static int displayWidth = 0;
private static int arrowWidth = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
horizontalScrollView = (HorizontalScrollView) findViewById(R.id.horizontalScrollView1);
linearLayout = (LinearLayout) findViewById(R.id.linearLayout1);
btnPrevious = (Button) findViewById(R.id.btnPrevoius);
btnNext = (Button) findViewById(R.id.btnNext);
for (int i = 0; i < 15; i++) {
Button button = new Button(this);
button.setTag(i);
button.setText("---");
linearLayout.addView(button);
}
ViewTreeObserver vto = linearLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewTreeObserver obs = linearLayout.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
Display display = getWindowManager().getDefaultDisplay();
displayWidth = display.getWidth();
if (linearLayout.getMeasuredWidth() > (displayWidth - 40)) {
btnPrevious.setVisibility(View.VISIBLE);
btnNext.setVisibility(View.VISIBLE);
}
}
});
btnPrevious.setOnClickListener(listnerLeftArrowButton);
horizontalScrollView.setOnTouchListener(listenerScrollViewTouch);
}
private OnTouchListener listenerScrollViewTouch = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
showHideViews();
return false;
}
};
private OnClickListener listnerLeftArrowButton = new OnClickListener() {
#Override
public void onClick(View v) {
horizontalScrollView.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(0, 0));
}
};
public static void showHideViews() {
int maxScrollX = horizontalScrollView.getChildAt(0).getMeasuredWidth()- displayWidth;
Log.e("TestProjectActivity", "scroll X = " +horizontalScrollView.getScrollX() );
Log.i("TestProjectActivity", "scroll Width = " +horizontalScrollView.getMeasuredWidth() );
Log.d("TestProjectActivity", "Max scroll X = " + maxScrollX);
if (horizontalScrollView.getScrollX() == 0) {
hideLeftArrow();
} else {
showLeftArrow();
}
if (horizontalScrollView.getScrollX() == maxScrollX) {
showRightArrow();
} else {
//hideRightArrow();
}
}
private static void hideLeftArrow() {
btnPrevious.setVisibility(View.GONE);
}
private static void showLeftArrow() {
btnPrevious.setVisibility(View.VISIBLE);
}
private static void hideRightArrow() {
btnNext.setVisibility(View.GONE);
}
private static void showRightArrow() {
btnNext.setVisibility(View.VISIBLE);
}
}
The 'maxScrollX' value is not correct for me.How to find maximum scrollvalue for this?
Thanks in Advance
This might come a bit late, but for anyone out there that will face this problem I suggest alternative solution(s).
First, use different component than HorizontalScrollView. Here are the options:
OPTION 1: Horizontal ListView - add this class to your project (create a separate package, something like com.yourproject.widgets). Also you'll need to create custom Adapter, see how that's done in this example. I suggest you create separate adapter class (exp. HorizontalListViewAdapter) and put it in already created com.yourproject.widgets package.
add this widget to your layout in the xml (put it between buttons that need to mimic the scrolling behavior) you'll need to add something like:
<com.yourproject.widgets.HorizontalListView
android:id="#+id/hList"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
reference this (along with the buttons) in the Activity/Fragment that utilizes the widget
HorizontalListView mHList = (HorizontalListView) findViewById (R.id.hList);
Button bPrevoius = (Button) findViewById (R.id.btnPrevoius);
Button bNext = (Button) findViewById (R.id.btnNext);
add onClickListeners to the Buttons. Use the scrollTo() function predefined in the HorizontalListView widget. As you can see in the code, it takes int dp value to scroll. Add positive values if you want to scroll in right (next), and use negative values if you want to scroll in left (previous):
bPrevoius.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//value 500 is arbitrarily given. if you want to achieve
//element-by-element scroll you should get the width of the
//previous element dynamically or if the elements of the
//list have uniform width just put that value instead
mHList.scrollTo(-500);
//if it's the first/last element you can bPrevoius.setEnabled(false)
}
});
bNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mHList.scrollTo(500);
}
});
OPTION 2: More up to date solution to this issue can be the new widget RecyclerView introduced in Android L (addition of android:scrollbars="vertical" seems that would do the trick; other than that should have conventional ListView behavior). For more info check the official documentation.
devu
Plz have a look at the following links
1) http://android-er.blogspot.in/2012/07/implement-gallery-like.html
2) http://androiddreamers.blogspot.in/2012/09/horizontal-scroll-view-example.html
3)http://code.google.com/p/mobyfactory-uiwidgets-android/
Let me know if u r facing any issues
Thanks
In titanium appcelerator, you can do this using scrollableView
var scrollableView = Ti.UI.createScrollableView({
showPagingControl:true,
scrollingEnabled: true,
top: 360
});
Then, you can run a loop of all images or any content that you have, and add them to this view.
for(loop) {
eval("var view"+i+"=Ti.UI.createView();");
profile_image = Ti.UI.createImageView({
image: result[0]['profile_image'],
left:15,
width:82,
height:104,
top: 0
});
eval("view"+i+".add(profile_image);");
eval("scrollableView.addView(view"+i+");");
}
mywin.add(scrollableView);

Categories

Resources