How to create grids using Total rows and columns in android dynamically - java

I am new to android. I want to build a grid based on total rows and columns and display in view.After creating a grid I need to place icon in one of the grid. The icon will come from the server URL. The grid should be like this below.
That created grid should fit in the screen. How do I do that? Can someone give me a code sample. Thanks in advance!!!

res/layout/ gridview_android_example_with_image.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<GridView
android:id="#+id/gridview_android_example"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:columnWidth="100dp"
android:gravity="center"
android:minHeight="90dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" />
</LinearLayout>
AndroidGridViewDisplayImages.java
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class AndroidGridViewDisplayImages extends AppCompatActivity {
GridView androidGridView;
// Dummy Array of images (Replace with your own values)
Integer[] imageIDs = {
R.drawable.email, R.drawable.mobile, R.drawable.alram,
R.drawable.android, R.drawable.wordpress, R.drawable.web,
R.drawable.email, R.drawable.mobile, R.drawable.alram,
R.drawable.android, R.drawable.wordpress, R.drawable.web,
R.drawable.email, R.drawable.mobile, R.drawable.alram,
R.drawable.android, R.drawable.wordpress, R.drawable.web,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview_android_example_with_image);
androidGridView = (GridView) findViewById(R.id.gridview_android_example);
androidGridView.setAdapter(new ImageAdapterGridView(this));
androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
Toast.makeText(getBaseContext(), "Grid Item " + (position + 1) + " Selected", Toast.LENGTH_LONG).show();
}
});
}
public class ImageAdapterGridView extends BaseAdapter {
private Context mContext;
public ImageAdapterGridView(Context c) {
mContext = c;
}
public int getCount() {
return imageIDs.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView mImageView;
if (convertView == null) {
mImageView = new ImageView(mContext);
mImageView.setLayoutParams(new GridView.LayoutParams(130, 130));
mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
mImageView.setPadding(16, 16, 16, 16);
} else {
mImageView = (ImageView) convertView;
}
mImageView.setImageResource(imageIDs[position]);
return mImageView;
}
}
}

Related

How to add different toast messages for each imageView which displayed using GridView in android

activity_main
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="8"
tools:ignore="MissingConstraints" />
ImageAdapter.java
package com.example.android.whattheemoticon;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
private Integer[] mThumbIds = {
R.drawable.smileys, R.drawable.animals,
R.drawable.food, R.drawable.activities,
R.drawable.symbols, R.drawable.objects,
R.drawable.travel, R.drawable.flags,
};
}
MainActivity.java
package com.example.android.whattheemoticon;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//display images using gridview.
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
//onClickListeners for each clickable imageViews.
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
//create toast for view when clicked.
Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
}
I'm trying to add toast message for each images which are displayed using GridView , i'm ended up adding the code for toast to work for each grid . And i have completed adding and displaying the images in GridView. Please help me out for how to display the right toast message for each image while clicked by an user.
#Rajashekar. Here is an example.
public class MainActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//display images using gridview.
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
final ArrayList<String> message = new ArrayList<>();
message.add("Message for image 0");
message.add("Message for image 1");
message.add("Message for image 2");
//onClickListeners for each clickable imageViews.
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
//create toast for view when clicked.
String mess = message.get(position);
Toast.makeText(MainActivity.this, "" + mess, Toast.LENGTH_SHORT).show();
}
});
}
}
Declare an array like this :
String arr[ImageCount] = {"Message for first image", "Message for second image"......};
Then use a function to print Toast Message like this :
public void showToast(int pos){
for(int i = 0; i<=pos; i++){
if(i == pos){
Toast.makeText(Context, arr[i], Toast.LENGTH_SHORT).show();
break;
}
}
}
Now call the function :
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
showToast(position);
}

Images not getting swiped?

I have made a gallery, in this when i open an image, say image1, in fullview and then swipe in right direction only the image next to image1 i.e image2 comes and the images following image2 are not shown and similar thing happens when i click in reverse direction of image1.
FullimageActivity.java
package com.example.android.helloapp;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.ImageView;
public class Full_ImageActivity extends AppCompatActivity {
float startXValue = 1;
ImageView fullImageView;
int position;
private Integer[] mImageIds = { R.drawable.gallery_one,R.drawable.gallery_two,R.drawable.gallery_three,R.drawable.gallery_four,R.drawable.gallery_five,
R.drawable.gallery_six,R.drawable.gallery_seven,R.drawable.gallery_eight,R.drawable.gallery_nine,R.drawable.gallery_ten,
R.drawable.gallery_eleven,R.drawable.gallery_twelve,R.drawable.gallery_thirteen,R.drawable.gallery_fourteen,R.drawable.gallery_fifteen,
R.drawable.gallery_sixteen,R.drawable.gallery_seventeen,R.drawable.gallery_eighteen,R.drawable.gallery_nineteen,
R.drawable.gallery_twenty,R.drawable.gallery_twenty_one,R.drawable.gallery_twenty_two,R.drawable.gallery_twenty_three,R.drawable.gallery_twenty_four,
R.drawable.gallery_twenty_five};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_full__image);
} else {
setContentView(R.layout.activity_full__image);
}
Intent i=getIntent();
position=i.getExtras().getInt("id");
ImageAdapter imageAdapter=new ImageAdapter(this);
fullImageView=(ImageView)findViewById(R.id.fullImageView);
fullImageView.setImageResource(imageAdapter.images[position]);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
setRequestedOrientation(orientation);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float endXValue=0;
float x1=event.getAxisValue(MotionEvent.AXIS_X);
int action= MotionEventCompat.getActionMasked(event);
switch (action){
case (MotionEvent.ACTION_DOWN):
startXValue=event.getAxisValue(MotionEvent.AXIS_X);
return true;
case (MotionEvent.ACTION_UP):
endXValue = event.getAxisValue(MotionEvent.AXIS_X);
if (endXValue > startXValue) {
if (endXValue - startXValue > 100) {
System.out.println("Left-Right");
if(position-1!=-1)
fullImageView.setImageResource(mImageIds[position-1]);
}
}else {
if (startXValue -endXValue> 100) {
System.out.println("Right-Left");
if(position+1!=mImageIds.length)
fullImageView.setImageResource(mImageIds[position+1]);
}
}
return true;
default:
return super.onTouchEvent(event);
}
}
}
fullimage.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_full__image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.helloapp.Full_ImageActivity">
<include layout="#layout/tool_bar"></include>
<ImageView
android:id="#+id/fullImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:layout_gravity="center"
/>
</LinearLayout>
ImageAdapter.java
package com.example.android.helloapp;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context context;
public Integer[] images={
R.drawable.gallery_one,R.drawable.gallery_two,R.drawable.gallery_three,R.drawable.gallery_four,R.drawable.gallery_five,
R.drawable.gallery_six,R.drawable.gallery_seven,R.drawable.gallery_eight,R.drawable.gallery_nine,R.drawable.gallery_ten,
R.drawable.gallery_eleven,R.drawable.gallery_twelve,R.drawable.gallery_thirteen,R.drawable.gallery_fourteen,R.drawable.gallery_fifteen,
R.drawable.gallery_sixteen,R.drawable.gallery_seventeen,R.drawable.gallery_eighteen,R.drawable.gallery_nineteen,
R.drawable.gallery_twenty,R.drawable.gallery_twenty_one,R.drawable.gallery_twenty_two,R.drawable.gallery_twenty_three,R.drawable.gallery_twenty_four,
R.drawable.gallery_twenty_five
};
public ImageAdapter(Context c){
context=c;
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object getItem(int position) {
return images[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView=new ImageView(context);
imageView.setImageResource(images[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setLayoutParams(new GridView.LayoutParams(240,240));
return imageView;
}
}
once you open any image let's assume position is 3
so go right and display position+1 image but the value of position is still 3 so next time again on swipe position+1 mean 4th image will be displayed
Solution : re-assign the new position value to position variable or use unary operators i.e. position-- or position++
What you're looking for is called ViewPager and it's already implemented in the support library, so you don't have to write all that code by yourself.
References:
https://developer.android.com/reference/android/support/v4/view/ViewPager.html
https://developer.android.com/training/animation/screen-slide.html

How can i make TextView selected in GridView based on clicked position?

I am using a fragment where i am using a GridView to generate some categories. When user selects a category i am replacing the previous fragment with a new fragment which is used to take the details of the category. But when i get back to the previous fragment where the categories are displayed i want to make the category selected on which the user previously clicked. I have tried to use selector but it is not working for me. Here goes my code.
Here is my layout xml file
<?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"
android:paddingTop="20dp"
>
<GridView
android:id="#+id/hindernisTypGridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:columnWidth="190dp"
android:verticalSpacing="20dp"
android:layout_below="#+id/topBar"
android:horizontalSpacing="5dp"
android:paddingLeft="32dp"
android:paddingRight="32dp"
/>
</LinearLayout>
Here is my custom xml for gridview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools=" http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="190dp"
android:layout_height="180dp"
android:padding="2dp"
tools:ignore="MissingPrefix"
>
<TextView
android:textColor="#color/redText"
android:textSize="37.14sp"
android:layout_gravity="center_horizontal"
android:gravity="center_vertical"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="180dp"
android:text="OBW"
android:id="#+id/hindernisTypTextView"
fontPath="DBSansRegular.otf"
android:textAppearance="#style/DBSansRegular"
android:background="#drawable/grid_view_item_selector"
/>
</RelativeLayout>
Here is my selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/redText" android:state_pressed="true"/>
</selector>
Here is the Fragment which is used to display the categories
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.adapters.HindernisTypGridViewAdapter;
import com.example.anikdey.railwayapp.models.HindernisTyp;
public class HindernisTypFragment extends Fragment {
private GridView projectListGridView;
private View view;
private HindernisTyp hindernisTyp;
private HindernisTypGridViewAdapter hindernisTypGridViewAdapter;
private OnHindernisTypSelectedListener hindernisTypSelectedListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.kategorie_wahlen_grid_view, container, false);
projectListGridView = (GridView) view.findViewById(R.id.kategoryWahlenGridView);
hindernisTyp = new HindernisTyp();
hindernisTypGridViewAdapter = new HindernisTypGridViewAdapter(getActivity().getApplicationContext(), hindernisTyp.getHindernisTyps());
projectListGridView.setAdapter(hindernisTypGridViewAdapter);
projectListGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
hindernisTypSelectedListener.setHindernisTyp(hindernisTyp.getHindernisTyps().get(position).getHindernisTypName());
FragmentManager fragmentManager = getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new DetailsFragment(),"DetailsFragment");
fragmentTransaction.addToBackStack("df");
fragmentTransaction.commit();
}
});
return view;
}
}
The adapter i have used for displaying the categories in gridview
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.models.HindernisTyp;
import java.util.ArrayList;
import java.util.List;
public class HindernisTypGridViewAdapter extends BaseAdapter {
private Context context;
private List<HindernisTyp> hindernisTyps = new ArrayList<HindernisTyp>();
public HindernisTypGridViewAdapter(Context context, List<HindernisTyp> hindernisTyps){
this.context = context;
this.hindernisTyps = hindernisTyps;
}
#Override
public int getCount() {
return hindernisTyps.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
private static final class ViewHolder {
private TextView hindernisTypTextView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.hindernis_typ_grid_view_custom_layout, null, true);
holder = new ViewHolder();
holder.hindernisTypTextView = (TextView) convertView.findViewById(R.id.hindernisTypTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.hindernisTypTextView.setText(hindernisTyps.get(position).getHindernisTypName());
return convertView;
}
}
When user going to details fragment send that selected category to main activity or shared preference or constant but not try to rely on onSaveInstanceState()
Now when you return to a fragment from the back stack it does not re-create the fragment but re-uses the same instance and starts with onCreateView() in the fragment lifecycle, see Fragment Lifecycle.
Now start form onCreateView()
So add a boolean isRestoredFromBackstack to fragment and follow code below:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mIsRestoredFromBackstack = false;
}
#Override
public void onResume()
{
super.onResume();
if(mIsRestoredFromBackstack)
{
// The fragment restored from backstack,
// get selected state and set category selected again!
}
}
#Override
public void onDestroyView()
{
super.onDestroyView();
mIsRestoredFromBackstack = true;
}
OR
there is another simple solution.... depends on situation
just use add() not replace()
Fragment fragment=new DestinationFragment();
FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction ft=fragmentManager.beginTransaction();
ft.add(R.id.content_frame, fragment);
ft.hide(SourceFragment.this);
ft.addToBackStack(SourceFragment.class.getName());
ft.commit();
Here is the way by which i have solved my problem. Before starting the new fragment i am storing the position in a variable named previousPosition which was initialized whit a negative value of -1. Then i am passing the previousPosition in the Adapter. The code is given below.
The updated Fragment class
package com.example.anikdey.railwayapp.fragments;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.adapters.HindernisTypGridViewAdapter;
import com.example.anikdey.railwayapp.models.HindernisTyp;
public class HindernisTypFragment extends Fragment {
private GridView projectListGridView;
private View view;
private HindernisTyp hindernisTyp;
private HindernisTypGridViewAdapter hindernisTypGridViewAdapter;
private OnHindernisTypSelectedListener hindernisTypSelectedListener;
private int previousPosition = -1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.kategorie_wahlen_grid_view, container, false);
projectListGridView = (GridView) view.findViewById(R.id.kategoryWahlenGridView);
hindernisTyp = new HindernisTyp();
hindernisTypGridViewAdapter = new HindernisTypGridViewAdapter(getActivity().getApplicationContext(), hindernisTyp.getHindernisTyps(), previousPosition);
projectListGridView.setAdapter(hindernisTypGridViewAdapter);
projectListGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
hindernisTypSelectedListener.setHindernisTyp(hindernisTyp.getHindernisTyps().get(position).getHindernisTypName());
hindernisTypSelectedListener.enableCancelButton(true);
previousPosition = position;
FragmentManager fragmentManager = getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new DetailsFragment(),"DetailsFragment");
fragmentTransaction.addToBackStack("df");
fragmentTransaction.commit();
}
});
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
hindernisTypSelectedListener = (OnHindernisTypSelectedListener) activity;
} catch (ClassCastException e) {
}
}
public interface OnHindernisTypSelectedListener {
public void setHindernisTyp(String hindernisTyp);
public void enableCancelButton(boolean state);
}
}
Here is the updated Adapter class
package com.example.anikdey.railwayapp.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.models.HindernisTyp;
import java.util.ArrayList;
import java.util.List;
public class HindernisTypGridViewAdapter extends BaseAdapter {
private Context context;
private int previousPosition;
private List<HindernisTyp> hindernisTyps = new ArrayList<HindernisTyp>();
public HindernisTypGridViewAdapter(Context context, List<HindernisTyp> hindernisTyps, int previousPosition){
this.context = context;
this.hindernisTyps = hindernisTyps;
this.previousPosition = previousPosition;
}
#Override
public int getCount() {
return hindernisTyps.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
private static final class ViewHolder {
private TextView hindernisTypTextView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.hindernis_typ_grid_view_custom_layout, null, true);
holder = new ViewHolder();
holder.hindernisTypTextView = (TextView) convertView.findViewById(R.id.hindernisTypTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(position == previousPosition) {
holder.hindernisTypTextView.setBackgroundColor(context.getResources().getColor(R.color.redText));
holder.hindernisTypTextView.setTextColor(context.getResources().getColor(R.color.whiteText));
holder.hindernisTypTextView.setText(hindernisTyps.get(position).getHindernisTypName());
} else {
holder.hindernisTypTextView.setText(hindernisTyps.get(position).getHindernisTypName());
}
return convertView;
}
}

Expandable Listview OnClickListeners

I am creating an app in android studios that requires the user to select a child item from an expandable listview on one activity and for it to be displayed on another activity. I'm new to java and android studios and still dont understand how to do this really. If anyone has any sample code or can help that would be great, thanks!
You should use the setOnChildClickListener method from the ExpandableListView class to create a ClickListener for the list elements and then use a Intent to open the new activity. The call to set the listener should be set after you've set the adapter for the ListView.
Here there's a tutorial for using a ExpandableListView and it shows how to set a ClickListener for the elements.
And here there's the Android developer's documentation which shows how to create and open a new Activity from a button's click.
**You should use the setOnChildClickListener method from the ExpandableListView class to create a ClickListener for the list elements and then use a Intent to open the new activity. The call to set the listener should be set after you've set the adapter for the ListView and create the xml file for child and parent.child will be Expandable TextView **
**layout file**
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
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="com.example.elite_android.explistview1.MainActivity">
<RelativeLayout
android:id="#+id/main_number_picker_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="17dp">
<NumberPicker
android:id="#+id/main_number_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Next" />
<TextView
android:id="#+id/main_txt_patient_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#id/main_number_picker"
android:text="Select number of patient"
android:textColor="#color/colorAccent"
android:layout_marginLeft="80dp"/>
</RelativeLayout>
<ExpandableListView
android:id="#+id/exp_Listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/main_number_picker_layout">
</ExpandableListView>
</RelativeLayout>
**Main Activity.java file**
package com.example.elite_android.explistview1;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.view.View.OnFocusChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.NumberPicker;
public class MainActivity extends AppCompatActivity {
ExpandableListView expandableListView;
private MyAdapter mAdapter;
ExpandableListView expand;
NumberPicker numberPicker;
private List<String> headerItems;
private ArrayList childDetails;
private HashMap<String, List<String>> childList;
private Context ctx;
EditText editText1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the EditText
editText1 = (EditText) findViewById(R.id.child_item);
// //set the onFocusChange listener
// // editText1.setOnFocusChangeListener(editText1.getOnFocusChangeListener());
//
//// //get reference to EditText
//// editText2 = (EditText) findViewById(R.id.sequence);
//// // set the on focusChange listner
//// editText2.setOnFocusChangeListener(editText2.getOnFocusChangeListener());
//
// //Generate list View from ArrayList;
//
//
// EditText editText = (EditText) findViewById(R.id.child_item);
// editText.requestFocus();
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
//
//
//// editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
// // #Override
// // public void onFocusChange(View v, boolean hasFocus) {
// // //editText.setOnFocusChangeListener();
// // return;
// // }
// //});
//
String[] numbers = new String[10];
for (int count = 0; count < 10; count++)
numbers[count] = String.valueOf(count);
numberPicker = (NumberPicker) findViewById(R.id.main_number_picker);
numberPicker.setMaxValue(numbers.length);
numberPicker.setMinValue(1);
numberPicker.setDisplayedValues(numbers);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
generateListItems(newVal);
loadRecycleView();
}
});
}
private void generateListItems(int childCount) {
if (headerItems != null)
headerItems.clear();
else
headerItems = new ArrayList<>();
if (childList != null)
childList.clear();
else
childList = new HashMap();
if (childDetails == null) {
childDetails = new ArrayList();
childDetails.add("Name");
childDetails.add("Age");
childDetails.add("Gender");
}
// Put header items
for (int count = 0; count < childCount; count++) {
headerItems.add(" Parent " + count);
childList.put(headerItems.get(count), childDetails);
}
}
private void loadRecycleView() {
if (expandableListView == null) {
expandableListView = (ExpandableListView) findViewById(R.id.exp_Listview);
mAdapter = new MyAdapter(this, headerItems, childList);
expandableListView.setAdapter(mAdapter);
} else {
expandableListView.invalidate();
mAdapter.setHeaderData(headerItems);
mAdapter.setListData(childList);
mAdapter.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
**Adapter class.java**
package com.example.elite_android.explistview1;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.view.View.OnFocusChangeListener;
/**
* Created by ELITE-ANDROID on 28-02-2017.
*/
// this is provides all needs methods implementing an Expandable List VIew
public class MyAdapter extends BaseExpandableListAdapter {
// We need some Variables here so therer are some Variables here
private List<String> header_titles; // This is for Representing the HeadLine(Array list)
private HashMap<String, List<String>> child_titles; // defin the HashMap for the child item how to Represent the Parent Handing so Hash Map, need some Variables
private Context ctx;
private NumberPicker numberPicker;
EditText editText;
View view;
private static LayoutInflater inflater = null;
//for initalized for all Variables we need some Constructor
public MyAdapter(Context context, List<String> header_titles, HashMap<String, List<String>> child_titles) {
super();
this.ctx = context;
this.child_titles = child_titles;
this.header_titles = header_titles;
}
public void refreshHeader_titles(List<String> events) {
this.header_titles.clear();
this.header_titles.addAll(header_titles);
notifyDataSetChanged();
}
;
#Override
// From this Override method How to Return how many elements are the Group count like parent
public int getGroupCount() {
return header_titles.size();
}
#Override
//here the number of child items are in each heading. There are three Heading - PAtien Name ,Age, Gender
public int getChildrenCount(int groupPosition) {
// Log.d("xxx", )
return child_titles.get(header_titles.get(groupPosition)).size(); //how to Return the size of HashMap
}
#Override
public Object getGroup(int groupPosition) {
return header_titles.get(groupPosition);
}
#Override
// here how to retuen child items on the particular headings and Positions.
public Object getChild(int groupPosition, int childPosition) {
return child_titles.get(header_titles.get(groupPosition)).get(childPosition);
}
#Override
//return the groupo position
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
// Here return the Group View
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// ListViewHolder viewHolder;
// if (view == null) {
// viewHolder = new ListViewHolder();
// LayoutInflater inflater = context.getLayoutInflater();
// view = inflater.inflate(R.layout.listitems, null, true);
// viewHolder.itmName = (TextView) view.findViewById(R.id.Item_name);
// viewHolder.itmPrice = (EditText) view.findViewById(R.id.Item_price);
// view.setTag(viewHolder);
// } else {
// viewHolder = (ListViewHolder) view.getTag();
//// loadSavedValues();
// }
// Here how to get the Heading Title here Decalered String Variables, now how to get title of heading from getGroup methods so simple call Backed Methods.
String title = (String) this.getGroup(groupPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.prent, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.heading_item);
textView.setText(title); // for Heading bold style ,title
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
String title = (String) this.getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child, null);
}
String cellData = child_titles.get(header_titles.get(groupPosition)).get(childPosition);
EditText childItem = (EditText) convertView.findViewById(R.id.child_item);
childItem.setHint(cellData);
childItem.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// Log.d("xxxx", "Has focus " + hasFocus);
if (!hasFocus) {
// int itemIndex = View.getId();
// String enteredName = ((EditText)v).getText().toString();
// selttems.put(itemIndex, enteredName);
} else {
}
return;
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void setListData(HashMap<String, List<String>> lData) {
child_titles = lData;
}
public void setHeaderData(List<String> hData) {
header_titles = hData;
}
}
**child.Xml file**
<?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="50dp"
android:background="#ffff">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/child_item"
android:textSize="25dp"
android:textStyle="bold"
android:gravity="center_vertical"
android:layout_marginLeft="10dp"/>
<!--<EditText-->
<!--android:id="#+id/sequence"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_alignParentLeft="true"-->
<!--android:layout_alignParentTop="true"-->
<!--android:paddingLeft="35sp"-->
<!--android:layout_marginRight="10dp"-->
<!--android:textAppearance="?android:attr/textAppearanceMedium" />-->
</LinearLayout>
<!--This Layout File Represent the Child Items.
This Field Represent the Child Item IN the List VIew -->
**parent.Xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="vertical">
<TextView
android:id="#+id/heading_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
android:textColor="#color/colorAccent"
android:textSize="25dp" />
</LinearLayout>
<!--This Layout file for Heading -Lines.-->

Adding swipe functionality and a textview to a Image Slideshow Android app - Comic

I need to add swipe functionality and a textview to a Image Slideshow Android App implementation - which is actually a comic about the life of St. Don Bosco with images that go along with the story. Gallery widget did the job but sadly now deprecated :(
I managed to do the following and navigation between images is only possible by clicking the thumbnails at the bottom:
Screenshots - Genymotion
Current Java:
package org.dbysmumbai.donbosco;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
public class MainActivity extends Activity implements
AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dbyouth_activity);
mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
mSwitcher.setImageResource(mImageIds[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
return i;
}
private ImageSwitcher mSwitcher;
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mThumbIds[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(R.drawable.empty_frame);
return i;
}
private Context mContext;
}
private Integer[] mThumbIds = {
R.drawable.dbyouth000, R.drawable.dbyouth001,
R.drawable.dbyouth001b, R.drawable.dbyouth002};
private Integer[] mImageIds = {
R.drawable.dbyouth000, R.drawable.dbyouth001, R.drawable.dbyouth001b,
R.drawable.dbyouth002};
}
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">
<ImageSwitcher android:id="#+id/switcher"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<Gallery android:id="#+id/gallery"
android:background="#55000000"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:gravity="center_vertical"
android:spacing="16dp"
/>
</RelativeLayout>
Thanks for reading. Any help/links will be greatly and irrevocably appreciated :)
EDIT:
I'm using this code example for a viewpager.. how can I add a textview at the bottom that will detail the story
please please explain by editing this code .. Thanks a lot :)
MainActivity.java
package com.manishkpr.viewpagerimagegallery;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
}
ImageAdapter.java
package com.manishkpr.viewpagerimagegallery;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
activity_main.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" >
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
There were no thumbnails available with this code example and no left/right arrow to indicate swiping. I don't know to implement those. Maybe some help please?
Hi There !!
Did you try android ViewPager component?
if not please go through this .Its a very useful component.It
solved all your problems.
1:
http://developer.android.com/training/animation/screen-slide.html
If gallery is giving problem then go for HorizontalScrollView component of android.
This project is divided in to three tasks. First one is building Grid View display of all the images. Second is showing selected grid image in full screen slider. And finally adding pinch zooming functionality to fullscreen image.
Check out this tutorial, may be helpful for you to achieve your target

Categories

Resources