One activitiy with different backgrounds in android - 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" >

Related

startActivity() inside setOnClickListener not doing anything

I have a button inside a view that checks some constraints, and then starts another activity, however the startActivity() call does not do anything, the new activity's onCreate() never gets called, and the code then continues past it. I have checked using logging and breakpoints, and the conditions are being met and startActivity() is being called. Both activities are defined in the application manifest.
From the source activity's onCreate():
int[] winning_player;
int next_player;
int[] scores;
[...]
final Button end_turn_button = (Button) findViewById(R.id.end_turn);
end_turn_button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (winning_player[0] == next_player) {
Intent intent = new Intent(getApplicationContext(), FinalScreenActivity.class);
intent.putExtra("SCORES", scores);
startActivity(intent);
}
}
});
FinalScreenActivity.java
public class FinalScreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_screen);
Intent intent = getIntent();
final int[] scores = intent.getIntArrayExtra("SCORES");
// put the scoreboard in ascending order
Arrays.sort(scores);
// find the scoreboard in the view
TableLayout scoreboard = (TableLayout) findViewById(R.id.scoreboard);
// get the string resources to be formatted
Resources res = getResources();
String player_name_format = res.getString(R.string.player);
// Set the scoreboard in the view
Log.d("brains.PlayActivity", "onCreate: Creating scoreboard");
// for each player entry in the scoreboard
for (int i = 0; i < scores.length; i++) {
Log.d("brains.PlayActivity", "onCreate: adding scoreboard entry "+String.valueOf(i));
// create 2 TextViews
TextView player_name = new TextView(FinalScreenActivity.this);
TextView player_score = new TextView(FinalScreenActivity.this);
// Set the size of the TextViews
player_name.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
// set the first one to the player's name string resource
player_name.setText(String.format(player_name_format, i + 1));
// set the second one to the player's score resource, which takes the score twice (once for the number itself, and once to work out which plural is needed)
player_score.setText(res.getQuantityString(R.plurals.brains, scores[i], scores[i]));
// Create a TableRow to put the score into
TableRow scoreboard_entry = new TableRow(FinalScreenActivity.this);
// Set the size of the TableRow
scoreboard_entry.setLayoutParams(new TableRow.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
// Add the TextViews to the TableRow
scoreboard_entry.addView(player_name);
scoreboard_entry.addView(player_score);
// Add the TableRow to the TableLayout
scoreboard.addView(scoreboard_entry);
}
// Get the title text
TextView title_text = (TextView) findViewById(R.id.title_text);
title_text.setText(res.getQuantityString(R.plurals.win_brains, scores[scores.length - 1], scores.length - 1, scores[scores.length - 1]));
// set the play again button
Button play_again_button = (Button) findViewById(R.id.play_again_button);
play_again_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), SelectPlayersActivity.class);
startActivity(intent);
}
});
}
}
and activity_final_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="uk.co.bluesapphiremedia.android.zombiedice.FinalScreenActivity"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/title_text"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="#+id/scoreboard"
android:layout_below="#+id/title_text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/play_again"
android:id="#+id/play_again_button"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
end_turn_button.setOnClickListener(this);
//override onClick() method in activity implement interface View.OnClickListner
public void onClick(View v) {
if(v.getId() == R.id.end_turn){
if (winning_player[0] == next_player) {
Intent intent = new Intent(this,FinalScreenActivity.class);
intent.putExtra("SCORES", scores);
startActivity(intent);
}
}
}

ImageView On click not firing at the 2nd click

I want to close a popup menu on clicking a imageview.But it is not working.
menuicon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (f == 1) {
f = 0;
mPopupMenu.setContentWidth(ContactsActivity.this.getWindowManager()
.getDefaultDisplay()
.getWidth() / 2);
mAdapter.notifyDataSetChanged();
mPopupMenu.setAnchorView(menuicon);
mPopupMenu.show();
} else {
mPopupMenu.dismiss();
f = 1;
}
}
});
When I click the menuicon first time the popup menu is displaying correctly.But when i click for the 2nd time the menu is not closing.I debugged my code and found that the imageview is actually not firing roe 2nd time.menuicon is an imageview.And here is xml code:
<ImageView
android:id="#+id/menuicon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="#drawable/menuicon"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
/>
Initial value of f is 1.
You need to call setModal(false) of mPopupMenu. It will call setFocusable of inner PopupWindow and allow you to get events in the background window.

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);
}

android: handler

I am developing a kind of memory game app, where initially the 6 buttons will show some figures. Then when the below MyCount5sec and handler operates, after 5 sec of waiting period for user to remember, the handler will invoke txtClearRun whereby all the texts on every buttons to be erased.
Then after the 5 sec waiting period, it comes the testing period. The user has to select the button in sequence, ie. the latter button value must need to be greater than the earlier button value.
If the user is sucessful (ie. pressed all 6 number buttons), the app should wait 1.5 sec according to postDelay? Yet it appears that there are no delays.
If the user is wrong, ie. pressed button with value smaller than the previous one, the user fails and the app should also wait 1.5sec, with the button highlighted in red. However, it seems that there are no such 1.5sec delay too. No highlighting in red neither.
Question
Why there appears no delays? TWO handlers cannot be invoked at the same time?
how could that be further modified?
Thanks a lot!!
private void setQup()
{
.....
MyCount5sec counter5sec = new MyCount5sec(6000,1000);
counter5sec.start();
handler.postDelayed(txtClearRun, 6000);
pressed = 0;
temp = 0;
final int txtClearRun1time = 1500; // set here!
button_space1.setText("reset press "+pressed);
Button11.setOnClickListener(new OnClickListener() {#Override
public void onClick(View v) {vibrate(); int i=0; Button11.setEnabled(false);
if (i == B0) {puttobutton(B0,0);} if (i == B1) {puttobutton(B1,1);} if (i == B2) {puttobutton(B2,2);}
if (i == B3) {puttobutton(B3,3);} if (i == B4) {puttobutton(B4,4);} if (i == B5) {puttobutton(B5,5);}
pressed = pressed + 1;
int buttonvalue = Integer.parseInt(Button11.getText().toString());
if (pressed >5)
{
TotalScores=TotalScores+20;
handler1.postDelayed(txtClearRun1, txtClearRun1time);
loadNextQup();
}
if (buttonvalue < temp)
{
Button11.setBackgroundResource(R.drawable.red_btn);
TotalScores=TotalScores-10;
handler1.postDelayed(txtClearRun1, txtClearRun1time);
loadNextQup();
}
temp = buttonvalue;
}});
......same for other buttons..
}
Runnable txtClearRun = new Runnable()
{
public void run() {blankbutton();} //remove text on buttons
};
Runnable txtClearRun1 = new Runnable()
{
public void run() {} // solely for wish to delay operations
};
private void loadNextQup()
{
if (TerminateOrNot ==0)
{
handler.removeCallbacks(txtClearRun);
handler1.removeCallbacks(txtClearRun1);
setQup();
}
....
}
I tried make a simple game working on your rules ;) Instead of shapes I used checking background colors and text. I hope you will understand it, maybe this will help you some.
This is full working project:
Class:
public class MainActivity extends Activity {
Button bt1, bt2, bt3, bt4, bt5, bt6, bt7, bt8, bt9, restart;
List<Button> listButtons;
Handler handler1;
List<Integer> buttonColors;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listButtons = new ArrayList<Button>();
listButtons.add(bt1 = (Button) findViewById(R.id.bt1));
listButtons.add(bt2 = (Button) findViewById(R.id.bt2));
listButtons.add(bt3 = (Button) findViewById(R.id.bt3));
listButtons.add(bt4 = (Button) findViewById(R.id.bt4));
listButtons.add(bt5 = (Button) findViewById(R.id.bt5));
listButtons.add(bt6 = (Button) findViewById(R.id.bt6));
listButtons.add(bt7 = (Button) findViewById(R.id.bt7));
listButtons.add(bt8 = (Button) findViewById(R.id.bt8));
listButtons.add(bt9 = (Button) findViewById(R.id.bt9));
setAllEnabled(false);
// add on click listeners
for (int i = 0; i < listButtons.size(); i++) {
final int index = i;
//final because i will need it deeper
final Button s = listButtons.get(i);
//on click
s.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//when user click on something then show the origini color and tap "x"
s.setBackgroundColor(buttonColors.get(index));
s.setText("x");
// get all checked
List<Button> listChecked = countChecked();
// if checked more == 2
if (listChecked.size() == 2) {
// check if the same text was checked
boolean btnsHasTheSameTextAndBackgroundTag = checkAllTextAndBackgroundTag(listChecked);
//if they dont have same color and text then reset them
if (!btnsHasTheSameTextAndBackgroundTag) {
for (Button b : listChecked) {
b.setText("");
b.setBackgroundColor(Color.parseColor("#565656"));
}
}
}
//finall if user clicked 3 the same colors
else if (listChecked.size() == 3) {
// check if the same text was checked
boolean btnsHasTheSameTextAndBackgroundTag = checkAllTextAndBackgroundTag(listChecked);
if (btnsHasTheSameTextAndBackgroundTag) {
for (Button b : listChecked) {
b.setVisibility(View.INVISIBLE);
b.setText("");
}
} else {
for (Button b : listChecked)
{b.setText("");
b.setBackgroundColor(Color.parseColor("#565656"));
}
}
}
}
private boolean checkAllTextAndBackgroundTag(List<Button> list) {
int number = (Integer) list.get(0).getTag();
for (Button b : list) {
// if one of them will fail
if (!b.getText().equals("x") || number != (Integer)b.getTag())
return false;
}
return true;
}
private List<Button> countChecked() {
List<Button> temp = new ArrayList<Button>();
for (Button b : listButtons) {
if (b.getText().equals("x"))
temp.add(b);
}
return temp;
}
});
}
restart = (Button) findViewById(R.id.bt_restart);
// we go on.. create list of colors
final List<Integer> colorList = new ArrayList<Integer>();
colorList.add(Color.parseColor("#C3C3E5"));
colorList.add(Color.parseColor("#F1F0FF"));
colorList.add(Color.parseColor("#8C489F"));
// on restart button action
restart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//enable all
setAllEnabled(true);
// remember new colors and create for it container
buttonColors = new ArrayList<Integer>();
// create random
Random r = new Random();
// get temp counter used colors
int[] wastedColor = new int[colorList.size()];
// for all buttons do the same job
for (int i = 0; i < listButtons.size(); i++) {
Log.d("xxx", i + "");
// take first random number
int numberRandom = r.nextInt(colorList.size());
// check if we have all colors with the same amount
while (wastedColor[numberRandom] == colorList.size())
numberRandom = r.nextInt(colorList.size());
// increment existing ones
wastedColor[numberRandom]++;
// remmeber this color
buttonColors.add(colorList.get(numberRandom));
listButtons.get(i).setTag(numberRandom);
listButtons.get(i).setBackgroundColor((int) (colorList.get(numberRandom)));
listButtons.get(i).setVisibility(View.VISIBLE);
}
// after generated colors...
handler1 = new Handler();
// hide after 5 sec
handler1.postDelayed(new HideAllColors(), 5000);
}
});
}
private void setAllEnabled(boolean status) {
for(Button b : listButtons)
b.setEnabled(status);
}
private class HideAllColors implements Runnable {
#Override
public void run() {
for (Button b : listButtons)
b.setBackgroundColor(Color.parseColor("#565656"));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="#+id/bt1"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:background="#565656" />
<Button
android:id="#+id/bt2"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:layout_toRightOf="#+id/bt1"
android:background="#565656" />
<Button
android:id="#+id/bt3"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:layout_toRightOf="#+id/bt2"
android:background="#565656" />
<Button
android:layout_margin="5dp"
android:id="#+id/bt4"
android:layout_below="#+id/bt1"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#565656" />
<Button
android:layout_margin="5dp"
android:id="#+id/bt5"
android:layout_below="#+id/bt2"
android:layout_toRightOf="#+id/bt4"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#565656" />
<Button
android:layout_margin="5dp"
android:id="#+id/bt6"
android:layout_below="#+id/bt3"
android:layout_toRightOf="#+id/bt5"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#565656" />
<Button
android:layout_margin="5dp"
android:id="#+id/bt7"
android:layout_below="#+id/bt4"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#565656" />
<Button
android:layout_margin="5dp"
android:id="#+id/bt8"
android:layout_below="#+id/bt5"
android:layout_toRightOf="#+id/bt7"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#565656" />
<Button
android:layout_margin="5dp"
android:id="#+id/bt9"
android:layout_below="#+id/bt6"
android:layout_toRightOf="#+id/bt8"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#565656" />
<Button
android:layout_margin="5dp"
android:id="#+id/bt_restart"
android:text="restart"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#565656" />
</RelativeLayout>

Dynamic set image path

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.

Categories

Resources