I have a problem with the GridView.
I would like to have a Grid with pictures and under each of them should be a timer. When I click one of the images, there should start the timer bellow of it.
How can I adapt TextViews and Images to a Gridview and let the TextView change every second.
I changed my code now to this
MainActivity
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends Activity implements Runnable{
/** The Constant INTERVALL. */
private static final int INTERVALL = 1000;
private ImageAdapter mAdapter;
private ArrayList<String> listText;
private ArrayList<Integer> listImage;
private GridView gridView;
/** The handler. */
private Handler handler = new Handler();
public boolean timerRuns = false;
public int time ;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
//GridView gridview = (GridView) findViewById(R.id.gridview);
//gridview.setAdapter(new ImageAdapter(this));
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new ImageAdapter(this, listText, listImage);
// Set custom adapter to gridview
gridView = (GridView) findViewById(R.id.gridView);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(MainActivity.this, mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public final void run() {
chronometer();
}
public void startTimer(View v) {
timerRuns = true;
time = 5*60;
update();
this.handler.postDelayed(this, INTERVALL);
}
public void stopTimer(View v) {
timerRuns = false;
handler.removeCallbacks(this);
}
public void chronometer(){
time = time -1;
update();
handler.postDelayed(this, INTERVALL);
}
private void update(){
updateScreen();
}
private void updateScreen(){
//TextView tvChronometer = (TextView)findViewById(R.id.tvChronometer);
//tvChronometer.setText(Integer.toString(time));
}
public void prepareList()
{
listText = new ArrayList<String>();
listText.add("Sample");
listText.add("Brazil");
listText.add("Canada");
listText.add("China");
listText.add("France");
listText.add("Germany");
listText.add("Iran");
listText.add("Italy");
listText.add("Japan");
listText.add("Korea");
listText.add("Mexico");
listText.add("Netherlands");
listText.add("Portugal");
listText.add("Russia");
listText.add("Saudi Arabia");
listText.add("Spain");
listText.add("Turkey");
listText.add("United Kingdom");
listText.add("United States");
listImage = new ArrayList<Integer>();
listImage.add(R.drawable.sample_0);
listImage.add(R.drawable.sample_3);
listImage.add(R.drawable.sample_3);
listImage.add(R.drawable.sample_7);
listImage.add(R.drawable.sample_1);
listImage.add(R.drawable.sample_6);
listImage.add(R.drawable.sample_2);
listImage.add(R.drawable.sample_7);
listImage.add(R.drawable.sample_4);
listImage.add(R.drawable.sample_5);
listImage.add(R.drawable.sample_0);
listImage.add(R.drawable.sample_5);
listImage.add(R.drawable.sample_0);
listImage.add(R.drawable.sample_2);
listImage.add(R.drawable.sample_1);
listImage.add(R.drawable.sample_4);
listImage.add(R.drawable.sample_3);
listImage.add(R.drawable.sample_1);
listImage.add(R.drawable.sample_6);
}
}
The ImageAdapter
`public class ImageAdapter extends BaseAdapter {
private ArrayList<String> listText;
private ArrayList<Integer> listImage;
private Activity activity;
public ImageAdapter(Activity activity,ArrayList<String> listText, ArrayList<Integer> listImage) {
super();
this.listText = listText;
this.listImage = listImage;
this.activity = activity;
}
#Override
public int getCount() {
return listText.size();
}
#Override
public String getItem(int position) {
return listText.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public static class ViewHolder
{
public ImageView imgView;
public TextView txtView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.element, null);
view.txtView = (TextView) convertView.findViewById(R.id.eText);
view.imgView = (ImageView) convertView.findViewById(R.id.eImage);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtView.setText(listText.get(position));
view.imgView.setImageResource(listImage.get(position));
return convertView;
}
}`
my gridview
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="110dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
and my element.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="#+id/eImage"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#color/Bisque" >
</ImageView>
<TextView
android:id="#+id/eText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="15sp" >
</TextView>
I hope you can help me.
1. Creating a gridview with text and image in each cell
Take a look at the documentation for GridView:
http://developer.android.com/guide/topics/ui/layout/gridview.html
The key method there is the public View getView(int position, View convertView, ViewGroup parent)
That method returns a view for each cell in the grid. You can create an XML layout that includes the TextView and ImageView. In the getView method for the adapter inflate the XML layout, attach an onClickListener so you can start the timer and return it as a view.
2. Updating the TextView from the grid
Keep in mind that a gridview contains contains multiple views, each of which can come from the same resource so this: TextView tvChronometer = (TextView)findViewById(R.id.tvChronometer); is not going to work in a gridview.
What you need to do is to get the specific view from the cell that you need (or iterate through all of them) and update the view. Something like this:
//First get the view for the cell assuming it's a composite view
View cellView = (TextView) gridview.getChildAt(position);
//Then get the actual TextView from that grid cell
TextView tvChronometer = cellView.findViewById(R.id.tvChronometer);
Although the best way in my opinion is to save a reference to the TextView when you a creating/instantiating it in the adapter.
Related
I am fairly new to Android and java. I am trying to make an application with multiple pages that you can swipe through. I started from a ViewPager2 example that is using a RecyclerView. It has 2 layout files. A main one and a viewPager one that is used for all the different pages, but with a different background color and title.
I have added a switch button on the viewpager xml and want to synchronize this button so it has the same state on all pages. But it does not do that out of the box. It seems the switch is created again for each of the different pages and I don't know how to access them on the other pages when the button on the current page is being changed.
It seems like a very simple thing to do, but I cannot find how to do it. Below is the code for my 2 java files.
Any help would be greatly appreciated.
public class MainActivity extends AppCompatActivity {
ViewPager2 viewPager2;
boolean continuous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager2 = findViewById(R.id.viewPager2);
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected (int position) {
if (continuous == true) continuous = false;
else continuous = true;
int pos = position;
}
});
List<String> list = new ArrayList<>();
list.add("First Screen");
list.add("Second Screen");
list.add("Third Screen");
list.add("Fourth Screen");
viewPager2.setAdapter(new ViewPagerAdapter(this, list, viewPager2));
}
}
public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewHolder> {
private List<String> mData;
private LayoutInflater mInflater;
private ViewPager2 viewPager2;
private int[] colorArray = new int[]{android.R.color.black, android.R.color.holo_blue_dark, android.R.color.holo_green_dark, android.R.color.holo_red_dark};
ViewPagerAdapter(Context context, List<String> data, ViewPager2 viewPager2) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.viewPager2 = viewPager2;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.item_viewpager, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
holder.relativeLayout.setBackgroundResource(colorArray[position]);
}
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView myTextView;
RelativeLayout relativeLayout;
Button button;
Switch switch2;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.tvTitle);
relativeLayout = itemView.findViewById(R.id.container);
button = itemView.findViewById(R.id.btnToggle);
switch2 = itemView.findViewById(R.id.switch2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(viewPager2.getOrientation() == ViewPager2.ORIENTATION_VERTICAL)
viewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
else{
viewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
}
}
});
switch2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (switch2.isChecked()) {
button.setEnabled(false);
} else {
button.setEnabled(true);
}
}
});
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/login"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="top|left"
app:tint="#color/white"
android:layout_margin="#dimen/small"
android:layout_marginTop="#dimen/small"
android:src="#drawable/ic_account_circle_24"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_bias="0.0"/>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/screen_viewpager"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="#+id/tab_indicator"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
This will help if you want to place the button on each page you should add it to your activity file and then place it on the position of the view pager
It seems like you are placing a different button on each page in the ViewPager but what you probably want is to place the button in the Activity layout?
Ok, I have an Listview adapter that contains an ImageView, TextView and another ImageView in that order. So I want to be able to delete the item in list when user presses on second ImageView. When the user press on the item in list it will start TextToSpeech and it will say what is inside TextView. But if the user wants to remove the entry he/she will press on second ImageView which is a delete icon, at that point the item will be remove from the list. Starting the click listener for the imageview is not a problem, the problem is how do I get the number (int) of the corresponding item in listview adapter so I can remove it from array. Here's xml list_item.xml for single entry in list
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp">
<ImageView
android:id="#+id/item_icon_imageview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.15"
android:src="#drawable/ic_record_voice_24dp2"/>
<TextView
android:id="#+id/phrase_textview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.80"
android:textSize="20sp"
android:layout_marginTop="5dp"
android:text="My phone number is 305 666 8454"/>
<ImageView
android:layout_gravity="center"
android:id="#+id/delte_item_imageview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.10"
android:src="#drawable/ic_delete_black_24dp"/>
</LinearLayout>
</RelativeLayout>
The fragment for inflating the listview
public class CustomFragment extends Fragment {
private ArrayAdapter<String> adapter;
private ListView listView;
private FloatingActionButton addPhraseButton;
private TextView phraseTitleTextView;
private TextToSpeech textToSpeech;
private ArrayList<String> phrases;
private static final String PHRASE_LABEL = " Phrases";
private static final String CATEGORY_KEY = "categories";
private ImageView deleteItemImageView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_custom, container, false);
final String categories;
//if we selecte a category sent from home fragment else we got here through menu
Bundle arguments = getArguments();
if (arguments != null && arguments.containsKey(CATEGORY_KEY)) {
categories = arguments.getString(CATEGORY_KEY).toLowerCase();
}
else {
Resources res = view.getResources();
categories = res.getStringArray(R.array.categories)[0].toLowerCase();
}
final Phrases allPhrases = Phrases.getPhrases();
allPhrases.fetchAllPhrases(view.getContext());
phrases = allPhrases.getAllPhrases().get(categories);
phraseTitleTextView = view.findViewById(R.id.label_phrases_txtview);
deleteItemImageView = view.findViewById(R.id.delte_item_imageview);
phraseTitleTextView.setText(categories.substring(0,1).toUpperCase() +
categories.substring(1)+ PHRASE_LABEL);
addPhraseButton = view.findViewById(R.id.add_phrases_btn);
// setting local for text to speech
textToSpeech = new TextToSpeech(getActivity().getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
textToSpeech.setLanguage(Locale.US);
}
});
//setting adapter and listview
adapter = new ArrayAdapter<String>(getContext(), R.layout.entry_item, R.id.phrase_textview, phrases);
listView = (ListView) view.findViewById(R.id.phrases_list);
listView.setAdapter(adapter);
listView.setItemsCanFocus(true);
//activating text to speech when user selects item in listview
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> paren, View view, int position, long id) {
String text = phrases.get(position);
Toast.makeText(getContext(), text, Toast.LENGTH_LONG).show();
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,null, null);
}
});
deleteItemImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
//button to display alert dialog box to add new phrase
addPhraseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addPhraseDialogBox();
}
});
return view;
}
}
You can achieve this through Custom Adapter. Check below:
public class CustomArrayAdapter extends ArrayAdapter<String> {
LayoutInflater inflater;
ArrayList<String> phrases;
public CustomArrayAdapter(Context context, int textViewResourceId, ArrayList<String> items) {
super(context, textViewResourceId, items);
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
phrases = items;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.entry_item, parent, false);
}
....
ImageView deleteItemImageview = (ImageView) convertView.findViewById(R.id. delte_item_imageview);
deleteItemImageview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
phrases.remove(position);
notifyDataSetChanged();
}
});
return convertView;
}
}
I want to create the following UI with a single list of dataset.
I tried using multiple view type but could not achieve my requirement. I also implemented this blog Android Horizontal and Vertical RecyclerView Example.
But this uses two recyclerviews and there are two sets of data (horizontal data and vertical data).
I also have tried this one. RecyclerView with multiple views using custom adapter in Android
But this is using static card views in XML and loading them in adapter.
I'm beginner in Android development. Please help!
Thank you in advance.
Your desired layout can be achieved by using a GridLayoutManager along with two "item view types" inside your RecyclerView.Adapter.
Here are my layout XML files:
activity_main.xml:
-------------------------
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
horizontal.xml:
-------------------------
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_margin="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/image"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ccc"/>
<TextView
android:id="#+id/text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:background="#fff"
android:textColor="#000"
android:textSize="18sp"
android:text="TEXT"/>
</LinearLayout>
</android.support.v7.widget.CardView>
vertical.xml:
-------------------------
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_margin="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#ccc"/>
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:background="#fff"
android:textColor="#000"
android:textSize="18sp"
android:text="TEXT"/>
</LinearLayout>
</android.support.v7.widget.CardView>
And here is my Java file:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridLayoutManager manager = new GridLayoutManager(this, 2);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return (position % 4) < 2 ? 2 : 1;
}
});
RecyclerView recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setLayoutManager(manager);
recycler.setAdapter(new MyAdapter());
}
private static class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
#Override
public int getItemViewType(int position) {
return (position % 4) < 2
? R.layout.horizontal
: R.layout.vertical;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(viewType, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.image.setImageResource(R.drawable.mouse);
holder.text.setText("" + position);
}
#Override
public int getItemCount() {
return Integer.MAX_VALUE;
}
}
private static class MyViewHolder extends RecyclerView.ViewHolder {
private final ImageView image;
private final TextView text;
public MyViewHolder(View itemView) {
super(itemView);
this.image = (ImageView) itemView.findViewById(R.id.image);
this.text = (TextView) itemView.findViewById(R.id.text);
}
}
}
Let's go over the important parts. First up is the combination of GridLayoutManager and SpanSizeLookup. We're creating the layout manager with this line:
GridLayoutManager manager = new GridLayoutManager(this, 2);
Which means that, by default, there will be two cards in each row of our grid. But then we apply the SpanSizeLookup, which says that half of our rows (found by the statement position % 4 < 2) should actually take up two columns. So we'll have one card, one card, two cards repeating in our "grid".
Then, in the RecyclerView.Adapter class, we override the getItemViewType() method. Here we again use the position % 4 < 2 statement to say that half of our views should be horizontal, and half should be vertical.
getItemViewType() just needs to return any unique int for each view type, so we use a nice trick of returning R.layout constants from this method. Since the view type will then be passed into onCreateViewHolder(), we can use the viewType argument to inflate the correct layout.
And that's it! Not too bad after all. Here's a screenshot of my code in action:
I had this issue not too long ago, though I may not be an expert I think my answer can help you as well. You can do this by creating two different types of layouts, similar to the article. You need to create an abstract class that both of the layout types can extend. Then, in your adapter, check what type of object should be shown.
Abstract class:
public abstract class ListItem {
public static final int TYPE_HORIZONTAL = 0;
public static final int TYPE_VERTICAL = 1;
abstract public int getType();
}
Horizontal Item:
public class HorizontalItem extends ListItem {
private String text;
private Bitmap image;
public HorizontalItem(String text, Bitmap image) {
this.text = text;
this.image = image;
}
/*
* Getter and setter methods here
*/
#Override
public int getType() {
return ListItem.TYPE_HORIZONTAL;
}
}
Vertical Item:
public class VerticalItem extends ListItem {
private String text1;
private Bitmap image1;
private String text2;
private Bitmap image2;
public VerticalItem(String text1, String text2, Bitmap image1, Bitmap image2) {
this.text1 = text1;
this.image1 = image1;
this.text2 = text2;
this.image2 = image2;
}
/*
* Getter and setter methods here
*/
#Override
public int getType() {
return ListItem.TYPE_HORIZONTAL;
}
}
Adapter:
public class ListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<ListItem> listItems;
public static class HorizontalViewHolder extends RecyclerView.ViewHolder {
public TextView text;
public ImageView imageView;
public HorizontalHolder(View v) {
super(v);
text = (TextView) v.findViewById(R.id.text);
imageView = (ImageView) v.findViewById(R.id.imageView);
}
}
public static class VerticalViewHolder extends RecyclerView.ViewHolder {
public TextView text1;
public ImageView imageView1;
public TextView text2;
public ImageView imageView2;
public HorizontalHolder(View v) {
super(v);
text1 = (TextView) v.findViewById(R.id.text1);
imageView1 = (ImageView) v.findViewById(R.id.imageView1);
text2 = (TextView) v.findViewById(R.id.text2);
imageView2 = (ImageView) v.findViewById(R.id.imageView2);
}
}
// constructor
public ListAdapter(ArrayList<ListItem> listItems) {
this.listItems = listItems;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
RecyclerView.ViewHolder holder = null;
switch (viewType) {
case ListItem.TYPE_HORIZONTAL:
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.template_horizontal, parent, false);
holder = new HorizontalViewHolder(v);
break;
case ListItem.TYPE_VERTICAL:
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.template_vertical, parent, false);
holder = new VerticalViewHolder(v);
break;
}
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case ListItem.TYPE_HORIZONTAL:
((HorizontalViewHolder) holder).text.setText(listItems.get(position).getText());
((HorizontalViewHolder) holder).imageView.setImageBitmap(listItems.get(position).getBitmap());
// the getText() and getBitmap() methods come from the getters of the HorizontalItems and VerticalItems that are stored in the ArrayList, listItems
break;
case ListItem.TYPE_DECK:
// Identical to above
break;
}
}
#Override
public int getItemCount() {
return listItems.size();
}
// This is extremely important, it is what lets the adapter know what type each listItem element is
#Override
public int getItemViewType(int position) {
return listItems.get(position).getType();
}
}
Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
// Must be of abstract type ListItem
ArrayList<ListItem> items = new ArrayList<>();
// populate your ArrayList
items.add(new HorizontalItem("text", bitmap));
items.add(new VerticalItem("text1", "text2", bitmap1, bitmap2));
// ... and so on
ListAdapter adapter = new ListAdapter(items)
RecyclerView recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setAdapter(adapter);
recycler.setLayoutManager(new LinearLayoutManager(this));
// ... the rest of your code below
}
In your layout for the vertical list item, I would just create one file with two halves to it. You can use a LinearLayout to easily divide the subsections into perfect halves.
So, here is the thing. I wanted to experiment a bit. So, i wrote this program which looks for images with (.jpg) extension in my mnt/shared/Newpictures folder in my GennyMotion Emulator. In my program, i captured the name of the files with .jpg extension in a String array adapter and the file path in a filepath string array. Now, here is the part where i am blank, i have the path,name and i can get the position by clicking on the list. But how do i open the image when i click on the list. I researched online and most of the codes were too confusing. So, may be someone can suggest me an easier approach. This is what i tried so far. Thanks.
package com.example.user.imageapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;
/**
* Created by user on 06-08-2015.
*/
public class Splash extends Activity {
Button load;
String s;
private ListView mainList;
private String[] FilePathStrings;
ArrayList<String>filesinFolder = GetFiles("/mnt/shared/NewPictures");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
// load = (Button)findViewById(R.id.Load);
mainList = (ListView) findViewById(R.id.imagelist);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,filesinFolder );
mainList.setAdapter(adapter);
mainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//what do i put here
}
});
}
public ArrayList<String> GetFiles(String DirectoryPath)
{
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
FilePathStrings = new String[files.length];
for (int i = 0; i < files.length; i++) {
// Get the path of the image file
if(files[i].getName().contains(".jpg")) {
FilePathStrings[i] = files[i].getAbsolutePath();
// Get the name image file
MyFiles.add(files[i].getName());
}
}
return MyFiles;
}
}
A simple way to achieve this would be to create a dialog containing an imageview and then set the imageview's image to the file. Something like this should do the job:
public void onItemclick(AdapterView<?> adapterView, View view, int pos, long id){
String filePath = filesInFolder.get(pos);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_img_preview, null);
builder.setView(view);
ImageView imgView = (ImageView)view.findViewById(R.id.preview_imgview);
imgView.setImageBitmap(BitmapFactory.decodeFile(filePath));
AlertDialog dialog = builder.create();
dialog.show();
}
Here is simple example, how you can view image by click on gridview but you can change to listview in xml file.
This is gridview display.
GridViewActivity.java
public class GridViewActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(GridViewActivity.this));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Send intent to SingleViewActivity
Intent i = new Intent(getApplicationContext(), SingleViewActivity.class);
// Pass image index
i.putExtra("id", position);
startActivity(i);
}
});
}
}
This class will display image in single page.
SingleViewActivity.java
public class SingleViewActivity extends Activity {
ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_view);
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.showImageForEmptyUri(R.mipmap.ic_launcher)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.bitmapConfig(Bitmap.Config.RGB_565).build();
// Get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.SingleView);
//imageView.setImageResource(imageAdapter.mThumbnames[position]);
imageLoader.displayImage(imageAdapter.mThumbnames[position],imageView,options);
}
}
i have used some random images from internet. This same concept is used in listview for displaying image.
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
ImageLoader imageLoader = ImageLoader.getInstance();
private DisplayImageOptions options;
// Constructor
public ImageAdapter(Context c) {
mContext = c;
layoutInflater = LayoutInflater.from(mContext);
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.showImageForEmptyUri(R.mipmap.ic_launcher)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.bitmapConfig(Bitmap.Config.RGB_565).build();
}
public int getCount() {
return mThumbnames.length;
}
public Integer getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder1 holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.grideview_item, null);
holder = new ViewHolder1();
holder.image = (ImageView) convertView.findViewById(R.id.imageView);
convertView.setTag(holder);
} else {
holder = (ViewHolder1) convertView.getTag();
}
// Load image, decode it to Bitmap and display Bitmap in ImageView (or any other view
// which implements ImageAware interface)
//imageLoader.displayImage("drawable://" + mThumbIds[position], holder.image);
imageLoader.displayImage(mThumbnames[position], holder.image, options);
//holder.image.setImageDrawable(mContext.getResources().getDrawable(mThumbIds[position]));
return convertView;
}
public static class ViewHolder1 {
ImageView image;
}
// Keep all Images in array
/* public Integer[] mThumbIds = {
R.drawable.ab, R.drawable.ac,
R.drawable.ad, R.drawable.ae
};*/
public String[] mThumbnames = {
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg",
"http://cdn2.ubergizmo.com/wp-content/uploads/2012/05/android_lock.jpg"
};
}
gridview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="10dp"
android:scaleType="fitXY" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_gravity="center|bottom"
android:layout_marginBottom="5dip"
android:background="#80000000"
android:gravity="center"
android:text="images"
android:textColor="#000000"
android:textSize="20dp" />
</FrameLayout>
I have an adapter with gridview that works as an Activity. I am trying to place it in a Fragment now and converted things but it does not work. When I include the IconFragmentSystem in my Activity I get a force close when I try to open the Activity.
I know the Activity works because I can use other Fragments and everything is okay so I know my issue lies within this file.
package com.designrifts.ultimatethemeui;
import com.designrifts.ultimatethemeui.R;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import java.util.ArrayList;
public class IconFragmentSystem extends Fragment implements AdapterView.OnItemClickListener{
private static final String RESULT_OK = null;
public Uri CONTENT_URI;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, container, false);
super.onCreate(savedInstanceState);
int iconSize=getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);
GridView gridview = (GridView) getActivity().findViewById(R.id.icon_grid);
gridview.setAdapter(new IconAdapter(this, iconSize));
gridview.setOnItemClickListener(this);
CONTENT_URI=Uri.parse("content://"+iconsProvider.class.getCanonicalName());
return view;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String icon=adapterView.getItemAtPosition(i).toString();
Intent result = new Intent(null, Uri.withAppendedPath(CONTENT_URI,icon));
setResult(RESULT_OK, result);
finish();
}
private void setResult(String resultOk, Intent result) {
// TODO Auto-generated method stub
}
private void finish() {
// TODO Auto-generated method stub
}
private class IconAdapter extends BaseAdapter{
private Context mContext;
private int mIconSize;
public IconAdapter(Context mContext, int iconsize) {
super();
this.mContext = mContext;
this.mIconSize = iconsize;
loadIcon();
}
public IconAdapter(IconFragmentSystem iconssystem, int iconSize) {
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
return mThumbs.size();
}
#Override
public Object getItem(int position) {
return mThumbs.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(mIconSize, mIconSize));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbs.get(position));
return imageView;
}
private ArrayList<Integer> mThumbs;
////////////////////////////////////////////////
private void loadIcon() {
mThumbs = new ArrayList<Integer>();
final Resources resources = getResources();
final String packageName = getActivity().getApplication().getPackageName();
addIcon(resources, packageName, R.array.systemicons);
}
private void addIcon(Resources resources, String packageName, int list) {
final String[] extras = resources.getStringArray(list);
for (String extra : extras) {
int res = resources.getIdentifier(extra, "drawable", packageName);
if (res != 0) {
final int thumbRes = resources.getIdentifier(extra,"drawable", packageName);
if (thumbRes != 0) {
mThumbs.add(thumbRes);
}
}
}
}
}
}
I have tried different ways to implement this but all have failed and I could really use help pointing me in the right direction.
This is my xml in layout
<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" >
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</RelativeLayout>
I was able to fix the issue
I changed
GridView gridview = (GridView) getActivity().findViewById(R.id.icon_grid);
to
GridView gridview = (GridView) view.findViewById(R.id.icon_grid);
and I also changed
gridview.setAdapter(new IconAdapter(this, iconSize));
to
gridview.setAdapter(new IconAdapter(getActivity(), iconSize));
Try this.
gridView = (GridView) rootView.findViewById(R.id.gridView);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,int pos, long l) {
// do something...
}
});
For more info, see this link:
Android gridview in fragment adapter constructor missing
GridView gridview = (GridView) getActivity().findViewById(R.id.icon_grid);
should be
GridView gridview = (GridView) container.findViewById(R.id.icon_grid);
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, container, false);
int iconSize = getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);
GridView gridview = (GridView) view.findViewById(R.id.icon_grid);
gridview.setAdapter(new IconAdapter(this, iconSize));
gridview.setOnItemClickListener(this);
CONTENT_URI = Uri.parse("content://"+iconsProvider.class.getCanonicalName());
return view;
}
Your going to want to remove the call to super, that is a leftover from you activity, the fragment does not call this method.