Click listview item and display image - java

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

Related

TextView doesn't change visually, but the date it keeps is correct

After login, I want to change text in TextView near profile on name_user.
But it doesn't change textView visually.
It is worth to mention, that when outputting (Toast), it gives out the data that is needed, but does not visually display it. Everything is fine with the TextView parameters (I think), because if you set the finished text in the parameters( i mean android:text="smth"), it visually displays it.
Java code:
`protected void onCreate(Bundle savedInstanceState) {
yourLayout = getLayoutInflater().inflate(R.layout.layout_navigation_header, null);
profileName = yourLayout.findViewById(R.id.profName); //
Intent intent = getIntent(); // Get data from previous activity.
String name_user = intent.getStringExtra("name");
String email_user = intent.getStringExtra("email");
String password_user = intent.getStringExtra("password");
profileName.setText(name_user); //0 changes, textView still don't change.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu2);
DrawerLayout drawerLayout = findViewById(R.id.drawerLayout);
Toast toast = Toast.makeText(getApplicationContext(), profileName.getText().toString(),
Toast.LENGTH_SHORT); // for debug, it works and show profileName that contains name_user, but.
toast.show();
findViewById(R.id.imageMenu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
}`
Part of main XML
`<com.google.android.material.navigation.NavigationView
android:id="#+id/navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="#layout/layout_navigation_header"// layour_navigation_header -here is TextView
app:menu='#menu/navigation_menu'
android:layout_gravity="start"/>`
Part of layour_navigation_header with TextView that I need to change.
`<TextView
android:id="#+id/profName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textColor="#color/black"
android:textSize="18sp"
android:text="Temporary"
app:layout_constraintBottom_toTopOf="#id/viewSupporter"
app:layout_constraintStart_toEndOf="#id/imageProfile"/>`
Hope you could help me
I tried to move
`yourLayout = getLayoutInflater().inflate(R.layout.layout_navigation_header, null);
profileName = yourLayout.findViewById(R.id.profName); //
Intent intent = getIntent(); // Get data from previous activity.
String name_user = intent.getStringExtra("name");
String email_user = intent.getStringExtra("email");
String password_user = intent.getStringExtra("password");
profileName.setText(name_user); //0 changes, textView still don't change`
before
`super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu2);`
but final result remains the same. It contains data, but not visually displays it.
You're inflating layout_navigation_header layout and setting a value in one of its textviews. But you never seem to place the layout on screen, the layout instance simply gets discarded.
What gets displayed is the activity_menu2 layout you inflate and set as content view with setContentView(). If that layout includes layout_navigation_header or its look-a-like with some mechanism, it's not the same instance you inflated earlier.
To solve the issue, just call setContentView() to set your desired layout, call findViewById() to find the textview and set a text to it.

Parsing the memory location of the source file of an ImageButton causes an error, why?

The ERROR I cannot justify
Say we have the memory location of a drawable (I stored that in a tag in the XML file) and we use it as a parameter for setImageResource(MEMORY_LOCATION). I can't make it work as the function is waiting for an int as input and by the time I parse it... I get an error
What I mean by memory location
The exact point I do not understand is Why does parsing a string representing a memory location to an int CAUSES AN ERROR?
If you want to find out why I want this or can suggest another way of solving the problem please read the full description
The problem I am trying to solve is to Find source from id
Say we have n ImageButtons and we want to pass their drawable to the next Activity.
One possible way would be using multiple case elements...
public class MainActivity extends Activity {
public static int chosen_button;
private ImageButton image_Button_1;
private ImageButton image_Button_2;
...
private ImageButton image_Button_n;
private final int possible_Buttons[] = {R.drawable.imgbtn1,R.drawable.imgbtn2,...,R.drawable.imgbtnn};
private View.OnClickListener tweakedOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.imgbtn1:
chosen_Button = possible_Buttons[0];
break;
case R.id.imgbtn2:
chosen_Button = possible_Buttons[1];
break;
...
case R.id.imgbtnn:
chosen_Button = possible_Buttons[n];
break;
default:
throw new RuntimeException("Unknown button ID");
}
Intent activity_Main_To_Secondary = new Intent(MainActivity.this, SecondaryActivity.class);
startActivity(activity_Main_To_Secondary);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image_Button_1 = findViewById(R.id.imgbtn1);
image_Button_2 = findViewById(R.id.imgbtn2);
image_Button_n = findViewById(R.id.imgbtnn);
image_Button_1.setOnClickListener(tweakedOnClickListener);
image_Button_2.setOnClickListener(tweakedOnClickListener);
image_Button_n.setOnClickListener(tweakedOnClickListener);
}
}
Then in order to get the drawable (as the ImageButton is only wired to the MainActivity via the XML file and is not wired to the SecondaryActivity at all) we can simply call the public int chosen_button and it works!
But with multiple case statements and multiple lines of code...
Another approach would be:
v.getId() gives the id, a memory location (I guess pointing to the XML file?)
R.drawable.triangle gives the src, a memory location pointing to the png file.
So as there is no function returning the memory location of the drawable by taking the id in, I tried setting the tag in the XML section file in the MainActivity to the memory location of each drawable. Looks like this:
<ImageButton
android:id="#+id/imgbtn1"
...
android:tag="‭2130903048"
<!-- Does it make any difference if it is written in hex, binary or decimal??? -->
android:src="#drawable/imgbtn1"
Everything works from when you try to v.getTag().toString() in MainActivity but by the time I try to parse it to an Int (or putExtra to the intent linking main and secondary activities) then the app breaks leading to the question of my post.
Intent activity_Main_To_Draw = getIntent();
String mem_location = activity_Main_To_Secondary.getStringExtra("$mem_loc");
Integer.parseInt(mem_location)

Android ListView - add HTML links when activity starts

I have an activity that displays a listview of html links, each stored in a TextView, that the user can add and remove links from by specifying a name and web address. Each link is stored in the listview in HTML, as below, and the user would click the word 'google' to start the web browser.
<a href='http://www.google.com'>google</a>
I have tried several ways to make the links do this, including android:autolink="web" in the XML file, with the method below being the only way that works. However, I cannot call it as the activity is initializing (from onCreate() or onStart()) as the getChildAt method returns null.
TextView wantedView = (TextView) listView.getChildAt(i);
wantedView.setText(Html.fromHtml(s));
wantedView.setClickable(true);
wantedView.setMovementMethod(LinkMovementMethod.getInstance());
However, if I set a clickable button that calls this code, then it works, although adding a new link to the list reverts the formatting.
Does anybody know why I can't access the TextView objects while initializing, and if there is another way to do this? I've posted my layout file and listview start up code below.
simplerow.xml <TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="15sp"
android:visibility="visible"
android:autoLink=""
android:gravity="center">
listview.xml <ListView
android:id="#+id/listView1"
android:layout_height="wrap_content"
android:layout_width="fill_parent" />
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test2);
listView1 = (ListView) findViewById(R.id.listView1);
items = new String[]{ "<a href='http://www.facebook.com'>facebook</a>",
"<a href='http://www.google.com'>google</a>",
"<a href='http://www.twitter.com'>twitter</a>" };
list = new ArrayList<>();
for(int i=0; i<items.length; i++) {
list.add(items[i]);
}
adapter = new ArrayAdapter<String>(Test.this, R.layout.simplerow, list);
listView1.setAdapter(adapter);
makeLinksVisible();
}
private void makeLinksVisible() {
int i = 0;
TextView wantedView = (TextView) listView.getChildAt(i);
while (wantedView != null) {
String s = wantedView.getText().toString();
wantedView.setText(Html.fromHtml(s));
wantedView.setClickable(true);
wantedView.setMovementMethod(LinkMovementMethod.getInstance());
i++;
wantedView = (TextView) listView.getChildAt(i);
}
}
Let you create the class extending ArrayAdapter<String>, and then override the getView(...) method. There you will have to have a LayoutInflatter and a View that refer to a single row (simply named row). This is the best place to execute row.setOnClickListener(new View.OnClickListener() {/*...*/}. Do not forget to create a holder if you will have a lot of displayed at once data.
More about custom ArrayAdapters e.g. here
The solution is to get the TextView from your ArrayAdapter, not your ListView. So if you are using a ListActivity, you would do something like:
ListView listView = getListView();
ArrayAdapter arrayAdapter = listView.getAdapter();
FrameLayout frameLayout = (FrameLayout) arrayAdapter.getView(0, null, null);
TextView wantedView = (TextView) frameLayout.findViewById(R.id.your_text_view);
wantedView.setText(Html.fromHtml(s));
wantedView.setClickable(true);
wantedView.setMovementMethod(LinkMovementMethod.getInstance());
This code of course assumes the use of a FrameLayout, but you would just replace that with whatever parent container holds your TextView that you are trying to access. Then in the getView() method, you would pass in the position of your TextView (I used zero just for an example). But if you try and use this code in your onCreate() it should work.
For any future viewers, here is a solution to the problem, and a brief description of how I found it.
I tried drschultz solution and noticed no change. He commented that using a textview with a string resource works. I tried this and realised the listview needed to be passed Spanned objects.
I found a solution for creating a Spanned Listview - here - and then added an onItemClickListener, which called setMovementMethod on the Textview object provided.
I realised that the previous solution wasn't working because the adapter's 'getview' method wasn't providing a reference to the listview object, instead it was providing a copy with the same data (I think). Overriding the onItemClick method is a quick solution to get a reference to the list object, which allows you to manipulate it directly and do whatever you like to it.
I've added the code I used to test this solution below. It creates a list of two html references. The first click of a textview calls the onItemClick method, then any more clicks will take you to the web page specified.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
String s = new String("facebook");
Spanned sp = Html.fromHtml(s);
String s1 = new String("google");
Spanned sp1 = Html.fromHtml(s1);
listValues = new ArrayList<>();
listValues.add(sp);
listValues.add(sp1);
setListAdapter(new SpannedAdapter(this, listValues));
ListView l = getListView();
l.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
try {
LinearLayout linearLayout = (LinearLayout) view;
TextView wantedView = (TextView) linearLayout.findViewById(R.id.rowTextView);
wantedView.setClickable(true);
wantedView.setMovementMethod(LinkMovementMethod.getInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

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.

Android ListView - onItemClickListener

I'm beginning in mobile application development and I want to know how to send an item from a ListView to appear in another activity; Then I can show more information about each item.
I managed to display the title and description with the following code:
MainActivity
TextView txt = (TextView)findViewById(R.id.textView1);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("title", txt.getText());
startActivity(intent);
SecondActivity
TextView txt = (TextView)findViewById(R.id.show_textView1);
Bundle b = this.getIntent().getExtras();
String val = b.getString("name");
txt.setText(val);
but how do I set putExtra for an image to display in the next Activity ?
P.S. everything is working fine, the xml file where the item details will be shown is set.
What is the source of the image?
If a file, pass in the String to the file location.
bundle.putString("file-loc",fileLocation);
If a resource, pass in the resource.
bundle.putInt("resource-id",resid);
If it's just a bitmap, you can actually pass it directly, as a Parcelable.
bundle.putParcelable("bitmap",bitmap);
You can send the ImageView's id (R.drawable.your_image) and then fetch it and show it in the ImageView of other activity

Categories

Resources