I'm having touble in making my random generated image (which is read as a button) become clickable which leads to each different activity for each different image. So the random images work perfect actually, the only problem it's not clickable Here's my code
final Button imgView = (Button)findViewById(R.id.top1);
Random rand = new Random();
int rndInt = rand.nextInt(4) + 1;
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setBackgroundResource(id);
On my layout, I specified the id top1 as a button.
So the above code will look up to my drawable images, which have the names 'img1.jpg', 'img2.jpg', 'img3.jpg' , and 'img4.jpg'.
So what I wanna make is something like, when 'img1.jpg' is generated, it becomes clickable and leads to for example: Activity1.java , for 'img2.jpg' the intent goes to 'Activity2.java', etc.
Thanks much in advance. I'm open for any kind of solution :)
UPDATED:
Here's the full code of my Main class:
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_x);
final Button imgView = (Button)findViewById(R.id.top1);
Random rand = new Random();
imgView.setOnClickListener(new ActivitySwitch(1,this));
imgView.setOnClickListener(new ActivitySwitch(2,this));
imgView.setOnClickListener(new ActivitySwitch(3,this));
imgView.setOnClickListener(new ActivitySwitch(4,this));
int rndInt = rand.nextInt(4) + 1;
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setBackgroundResource(id);
}
and here the ActivitySwitch class:
public class ActivitySwitch implements OnClickListener{
int imageNo;
Context context;
public ActivitySwitch(int imageNo,Context context) {
super();
this.context=context;
this.imageNo = imageNo;
}
#Override
public void onClick(View v) {
Intent it=new Intent();
if(imageNo==1)
{
it.setClass(context, ProjektAID.class);
}
else if (imageNo==2)
{
it.setClass(context, ProjektADH.class);
}
else if (imageNo==3)
{
it.setClass(context, ProjektBOS.class);
}
else if (imageNo==4)
{
it.setClass(context, ProjektBROT.class);
}
}
}
There is a way: create a new class
class ActivitySwitch implements OnClickListener{
int imageNo;
Activity context
public ActivitySwitch(int imageNo,Context context) {
super();
this.context=(Activity)context;
this.imageNo = imageNo;
}
#Override
public void onClick(View v) {
Intent it=new Intent();
if(imageNo==1){
it.setClass(context, Activity1.class);
}
else{
.......
}
startActivityForResult(it,any_integer_value);
}
}
And then in the Activity set:
imgView.setOnClickListener(new ActivitySwitcher(randInt,this);
if this is a button, simple implement the function of onclicklistener of button and call the respective activity from text it gets... ping me if u didn't understand..
Related
I have RecyclerView + cards. In the cards I set the random color in class ViewHolder -
` int[] androidColors = view.getResources().getIntArray(R.array.androidColors);
int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
if (frameLayout != null) {
frameLayout.setBackgroundColor(randomAndroidColor);
}`
By clicking on the card, open activity. And the color of her toolbar should be like that of a card.
Intent putExtra I can not use here, because in the intent, I already pass the tag.
public ViewHolder(View itemView) {
....
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long poemId = (Long) v.getTag();
onPoemClickListener.onPoemClick(poemId);
}
});
}
}
public interface OnPoemClickListener {
void onPoemClick(long poemId);
}
fragment class where recycler is located
private final PoemsAdapter.OnPoemClickListener onPoemClickListener = new PoemsAdapter.OnPoemClickListener() {
#Override
public void onPoemClick(long poemId) {
Intent intent = new Intent(getActivity(), ReadActivity.class);
intent.putExtra(ReadActivity.EXTRA_POEM_ID, poemId);
startActivity(intent);
}
};
How can I get the random color that I generate in the adapter in activity? Thank!
You can put as many extras as you want:
Intent intent = new Intent(getActivity(), ReadActivity.class);
intent.putExtra(ReadActivity.EXTRA_POEM_ID, poemId);
intent.putExtra("mycolor", color);
startActivity(intent);
then get it in the activity that opens, just like you get any other extra value,
I have a set of array which i am displaying in imageview during a specified interval of time.What i want when i click image i want to show that image in another activity.How can i do that
code:-
int[] imageArray = {R.drawable.amazon, R.drawable.app_me,
R.drawable.borabora, R.drawable.dubai};
public void showImage(){
m_oHandler = new Handler();
Runnable oRunnable = new Runnable() {
int i = 0;
#Override
public void run() {
img.setImageResource(imageArray[i]);
i++;
if (i > imageArray.length - 1) {
i = 0;
}
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Didn't know where to go
Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra("BitmapImage", imageArray);
}
});
m_oHandler.postDelayed(this, 6000);
}
};
m_oHandler.postDelayed(oRunnable, 6000);
}
Do Not Pass Bitmap object.
Instead pass id of drawable resources.
Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra("image_res_ids", CollectonUtils.join("/", imageArray);
And in Second Activity,
getIntent().getExtra("image_res_ids");
to get image resource id array.
want when i click image i want to show that image in another activity.
Use img setTag() method for saving current drawable id and get it back on click of view using getTag()
1. set drawable id using setTag:
....
img.setImageResource(imageArray[i]);
img.setTag(imageArray[i]);
....
2. Get id from v inside onClick method:
int click_drawable_id=Integer.parseInt(v.getTag().toString());
intent.putExtra("clicked_img_draw_id", click_drawable_id);
Now instead of passing imageArray Array, just use clicked_img_draw_id to get drawable id and pass it to setImageResource to show clicked image in another Activity.
Your images are drawable resources, which are nothing more that an int. So you can definitely pass them as extras in an Intent.
You can send the array as an extra and then fetch it with getIntent().getIntArrayExtra(EXTRA_IMAGE)
For more details have a look at Intents
you save the index/resource id using setTag i.e do img.setTag(index) as follows.
And fowarding it you can remove the index/resource id from tag and pass as intent extra
#Override
public void run() {
img.setImageResource(imageArray[i]);
img.setTag(i)
i++;
//your code
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Didn't know where to go
Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra("IMAGE_RESOURCE", img.getTag());
}
});
just try to send position of your selected image
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
get intent
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
Check this for more http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/
If you want to pass single image to next activity, than in your case, only pass image index like
Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra("BitmapImage", imageArray[i]);
and on next activity get it. like
int image_id= getIntent().getIntExtra("BitmapImage",0);
this image_id is your selected image resouce id and you can set this as setImageresouce to image view.
previewView = (ImageView) findViewById(R.id.imgPostIssue);
First Activity
Intent intent = new Intent(AddNewIssue.this, PostNewIssue.class);
intent.putExtra("picture", byteArray);
finish();
startActivity(intent);
Second Activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
byte[] byteArray = extras.getByteArray("picture");
if (byteArray != null) {
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imgPostIssue);
image.setImageBitmap(bmp);
}
}
Try this out, it will definitely work.. Hope it will help you.
Try using setTag(). Check this out
BitmapCache.java
public class BitmapCache {
private static SparseArray<Bitmap> _bitmapCache = new SparseArray<>();
public static void fillBitmapCache(#NonNull Resources resources) {
if (null == _bitmapCache)
_bitmapCache = new SparseArray<>();
if (_bitmapCache.indexOfKey(R.drawable.amazon) < 0)
_bitmapCache.append(R.drawable.amazon, BitmapFactory.decodeResource(resources, R.drawable.amazon));
if (_bitmapCache.indexOfKey(R.drawable.app_me) < 0)
_bitmapCache.put(R.drawable.app_me, BitmapFactory.decodeResource(resources, R.drawable.app_me));
if (_bitmapCache.indexOfKey(R.drawable.borabora) < 0)
_bitmapCache.put(R.drawable.borabora, BitmapFactory.decodeResource(resources, R.drawable.borabora));
if (_bitmapCache.indexOfKey(R.drawable.dubai) < 0)
_bitmapCache.put(R.drawable.dubai, BitmapFactory.decodeResource(resources, R.drawable.dubai));
}
public static Bitmap getAt(int position) {
return get(keyAt(position));
}
public static int keyAt(int position) {
return _bitmapCache.keyAt(position);
}
public static Bitmap get(#DrawableRes int resId) {
return _bitmapCache.get(resId);
}
public static boolean has(#DrawableRes int resId) {
return _bitmapCache.indexOfKey(resId) < 0;
}
public static void append(#DrawableRes int resId, #NonNull Resources resources) {
_bitmapCache.append(resId, BitmapFactory.decodeResource(resources, resId));
}
public static void put(#DrawableRes int resId, #NonNull Resources resources) {
_bitmapCache.put(resId, BitmapFactory.decodeResource(resources, resId));
}
public static int size() {
return _bitmapCache.size();
}
}
Activity First
private void showImage() {
BitmapCache.fillBitmapCache(getResources());
m_oHandler = new Handler();
Runnable oRunnable = new Runnable() {
int i = 0;
#Override
public void run() {
img.setImageBitmap(BitmapCache.getAt(i));
img.setTag(BitmapCache.keyAt(i));
i++;
if (i >= BitmapCache.size()) {
i = 0;
}
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != v.getTag()) {
int resId = (int) v.getTag();
Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra("BitmapImage", resId);
}
}
});
m_oHandler.postDelayed(this, 6000);
}
};
m_oHandler.postDelayed(oRunnable, 6000);
}
Second Activity
private void displayImageOnSecond() {
Bundle bundle = getIntent().getExtras();
int resId = bundle.getInt("BitmapImage", 0);
if (resId > 0) {
secondImage.setImageBitmap(BitmapCache.get(resId));
}
}
Also I recommend to use ViewPager and customize it for auto rotate rather than the one you using currently. Runnable may cause memory leaks if Activity has been destroyed
My app is crashing at the end of the array in bluestacks. I have no idea why.
When I click the next button at the end of the array, the app crashes. I also tested it on my phone, same result. The rest of the app functions as intended.
From what I know "i %= image_elements.length;" is supposed to be the function that loops the array.
I am pretty sure this is where the crash is coming from.
i++;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
i %= image_elements.length;
Full code below
public class Practice extends MainMenuActivity {
int i = 0;
final int[] image_elements = {
R.drawable.spr_elements_0,
R.drawable.spr_elements_1,
[...]
R.drawable.spr_elements_86,
R.drawable.spr_elements_87,
};
final int[] image_names = {
R.drawable.spr_name_0,
R.drawable.spr_name_1,
[...]
R.drawable.spr_name_86,
R.drawable.spr_name_87,
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practice);
final ImageView element = (ImageView) findViewById(R.id.element);
final ImageView name = (ImageView) findViewById(R.id.name);
Button nextButton = (Button) findViewById(R.id.buttonNext);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
i++;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
i %= image_elements.length;
}
});
}
public void backButton(View view) {
Intent z = new Intent(this, MainMenuActivity.class);
startActivity(z);
}
}
You'll need to rearrange your code from this:
i++;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
i %= image_elements.length;
to this:
i++;
i %= image_elements.length;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
What happens otherwise is that the index is incremented beyond the boundaries of the array, and that is corrected afterwards with the modulus operator. You'll need to the the correction before you use the index.
i %= image_elements.length in this particular case, is essentially the same as
if( i == image_elements.length ) {
i = 0;
}
Arrays indices go from 0 to length-1.
You could get rid of the arrays entirely by looking up the resources by name, such as this:
final static int MAX_ELEMENTS = 88; // this includes 0..87
private int index = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practice);
final ImageView element = (ImageView) findViewById(R.id.element);
final ImageView name = (ImageView) findViewById(R.id.name);
final Resources res = this.getResources();
final String pkgName = this.getPackageName();
Button nextButton = (Button) findViewById(R.id.buttonNext);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final int imgId = res.getIdentifier( "spr_elements_" + index, "drawable", pkgName );
final int nameId = res.getIdentifier( "spr_name_" + index, "drawable", pkgName );
element.setImageResource( imgId );
name.setImageResource( nameId );
index = (index+1) % MAX_ELEMENTS;
}
});
}
I'm trying set Image from another activity's string.
My string on MainActivity
public static String imagee; // -- this is out of onCreate
capeMod.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
MainActivity.imagee = "drawable/pc";
Intent intent = new Intent(context, ModActivity.class);
startActivity(intent);
}
});
On another activity: (yeah, this is completely wrong.)
String imagee = MainActivity.imagee;
private void showImage() {
// int imageResource = R.drawable.icon;
int imageResource = getResources().getIdentifier(imagee, null, getPackageName());
Drawable imagee = getResources().getDrawable(imageResource);
image.setImageDrawable(image);
}
I can set TextView from another activity's string but couldnt set ImageView.How can i solve issue?
Instead of using a String I suggest using the id (which is an int) directly
MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
Button capeMod = (Button)findViewById(R.id.capemod);
capeMod.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this, ModActivity.class);
intent.putExtra(ModActivity.EXTRA_DRAWABLE_ID, R.drawable.pc);
startActivity(intent);
}
}
}
}
ModActivity:
public class ModActivity extends Activity {
public static final String EXTRA_DRAWABLE_ID = "drawableId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout2);
Bundle bundle = getIntent().getExtras();
int drawableId = bundle.getInt(EXTRA_DRAWABLE_ID);
ImageView imageView = (ImageView)findViewById(R.id.myImageView);
imageView.setImageResource(drawableId);
}
}
You can use the Intent.putExtra() to send data as well as String, and in other Activity use Intent.getExtras() to receive the data. Read more here
There is a way to do it. You need to place variable name as
imagee = "pc"; //inside drawable folder.
int resourceId = Activity.getResources().getIdentifier(imagee , "drawable", "your.package.name"); // package name can get by code also.
Drawable imagee = getResources().getDrawable(imageResource);
image.setImageDrawable(image);
Try this code that will work.
You should use something like this:
assuming that you can access to the string value doing like you did with the static string, use resources:
Resources res = getResources();
String imageName= MainActivity.imagee;
int resID = res.getIdentifier(imageName, "drawable", getPackageName());
Drawable drawable = res.getDrawable(resID );
image.setImageDrawable(drawable);
EDIT: even if it works, the correct way to access a value is not through static way, is always better to go via Intents and putExtra :)
I want to pass some data from one activity to another and set it in dynamically created TextView over frame layout of that activity..I'm using intent for that but at second activity the data is not getting extracted..Can any one tell me the simple way for this..
Following is my code..
Hidden.java
public class Hidden extends Activity implements OnClickListener {
Button btnnameadd, btnnameremove, btnmobileadd, btnmobileremove, btndone;
EditText etname, etmobile;
ImageView ivlogo;
private AlertDialog dialog;
private Uri mImageCaptureUri;
Intent jump;
//options for image selection
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
LinearLayout llname, llmobile, llimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hidden);
captureImageInitialization();
init();
}
private void init() {
etname=(EditText)findViewById(R.id.editTextname);
etmobile=(EditText)findViewById(R.id.editTextmobile);
btnnameadd=(Button)findViewById(R.id.buttonnameadd);
btnnameremove=(Button)findViewById(R.id.buttonnameremove);
btnmobileadd=(Button)findViewById(R.id.buttonmobileadd);
btnmobileremove=(Button)findViewById(R.id.buttonmobileremove);
btndone=(Button)findViewById(R.id.buttondone);
llname=(LinearLayout)findViewById(R.id.name);
llmobile=(LinearLayout)findViewById(R.id.mobile);
btnnameadd.setOnClickListener(this);
btnnameadd.setOnClickListener(this);
btnnameremove.setOnClickListener(this);
btnmobileadd.setOnClickListener(this);
btnmobileremove.setOnClickListener(this);
btndone.setOnClickListener(this);
}
#Override
public void onClick(View v) {
jump=new Intent(Hidden.this,Framelayout.class);
if(v.getId()==R.id.buttonnameadd)
{
String strname=etname.getText().toString();
Log.d("Log",strname);
jump.putExtra("Name",strname);
}else if(v.getId()==R.id.buttonnameremove)
{
btnnameremove.setEnabled(false);
llname.removeView(findViewById(R.id.editTextname));
}else if(v.getId()==R.id.buttonmobileadd)
{
String strmobile=etmobile.getText().toString();
Log.d("Log",strmobile);
jump.putExtra("Mobile",strmobile);
Log.d("LOG",jump.putExtra("Mobile",strmobile).toString());
}else if(v.getId()==R.id.buttonmobileremove)
{
llmobile.removeView(findViewById(R.id.editTextmobile));
}else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
}
}
FrameLayout.java
public class Framelayout extends Activity implements OnClickListener {
FrameLayout frameLayout;
Button b2,b3;
//private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_framelayout);
frameLayout = (FrameLayout)findViewById(R.id.f1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.buttonload);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId()==R.id.button2){
Intent i=new Intent(Framelayout.this,Hidden.class);
startActivity(i);
}else if(v.getId()==R.id.buttonload){
Log.d("Log",getIntent().getStringExtra("Name"));
editframelayout();
}
}
private void editframelayout() {
String name=getIntent().getExtras().getString("Name");
String mobile=getIntent().getExtras().getString("Mobile");
TextView tvname=new TextView(this);
tvname.setText(name);
tvname.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvname.setGravity(Gravity.CENTER);
TextView tvmobile=new TextView(this);
tvmobile.setText(mobile);
tvmobile.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvmobile.setGravity(Gravity.CENTER);
frameLayout.addView(tvname);
frameLayout.addView(tvmobile);
}
}
You must use one of putExtra() overloaded methods of the intent instance you created to add your data.
Here is a sample:
Intent intent = new Intent(this, SignoutActivity.class); // # this parameter is the context of the caller
intent.putExtra("PARAM_TEXTBOX_TEXT", textboxText);
startActivity(intent);
Edit for the code you added, your design is very poor and doesn't accomplish what is intended.
Every time you click a Button a new instance of Intent is created. you are calling startActivity() only in single case:
else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
Now you assume that the parameters added in previous button clicks are still there, but they aren't. When you click buttondone you create a new instance of Intent with no extras at all.
You can work this around as follows:
...
else if(v.getId()==R.id.buttondone)
{
String strname = etname.getText().toString();
if (strname != null && !strname.equals(""))
{
jump.putExtra("Name",strname);
}
String strmobile = etmobile.getText().toString();
if (strmobile != null && !strmobile.equals(""))
{
jump.putExtra("Mobile",strmobile);
}
startActivity(jump);
}
It still isn't well structured, but might do the trick for you
Use getIntent().getStringExtra("Name") instead of getIntent().getExtras().getString("Name");
getIntent().getStringExtra("Name")