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
Related
Even though I checked some threads, I'm having problems to use both the OnTouchListener and the OnClickListener inside of a fragment.
Custom class:
import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class Gestures implements View.OnTouchListener
{
private GestureDetector gestureDetector = null;
public Gestures()
{
gestureDetector = new GestureDetector(new GestureListener());
}
public boolean onTouch(View view, MotionEvent motionEvent)
{
boolean res = gestureDetector.onTouchEvent(motionEvent);
return res;
}
private final class GestureListener extends GestureDetector.SimpleOnGestureListener
{
private static final int SWIPE_THRESHOLD = 50;
private static final int SWIPE_VELOCITY_THRESHOLD = 50;
#Override
public void onLongPress(MotionEvent motionEvent)
{
onLongClick();
super.onLongPress(motionEvent);
}
#Override
public boolean onDown(MotionEvent motionEvent)
{
return true;
}
#Override
public boolean onFling(MotionEvent motionEvent1, MotionEvent motionEvent2, float velocityX, float velocityY)
{
boolean result = false;
try
{
float differenceX = motionEvent2.getX() - motionEvent1.getX();
float differenceY = motionEvent2.getY() - motionEvent1.getY();
if (Math.abs(differenceX) < Math.abs(differenceY))
{
if (Math.abs(differenceY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD)
{
if (differenceY > 0)
{
result = onSwipeBottom();
}
else
{
result = onSwipeTop();
}
}
else
{
result = nothing();
}
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
return result;
}
}
public boolean nothing()
{
return false;
}
public boolean onSwipeTop()
{
return false;
}
public boolean onSwipeBottom()
{
return false;
}
public boolean onLongClick()
{
return false;
}
}
Fragment:
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
public class Fragment1 extends Fragment implements View.OnClickListener, View.OnTouchListener
{
ConstraintLayout constraintLayoutOne, constraintLayoutTwo;
#Override public void onResume()
{
super.onResume();
constraintLayoutOne = getActivity().findViewById(R.id.constraint_layout_one); // Link variable to ID
constraintLayoutTwo = getActivity().findViewById(R.id.constraint_layout_two); // Link variable to ID
getActivity().findViewById(R.id.constraint_layout_one).setOnClickListener(this);
getActivity().findViewById(R.id.constraint_layout_two).setOnClickListener(this);
getActivity().findViewById(R.id.constraint_layout_one).setOnTouchListener(this);
getActivity().findViewById(R.id.constraint_layout_two).setOnTouchListener(this);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View fragment1 = inflater.inflate(R.layout.fragment1, container, false); // Link view and layout
return fragment1;
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent)
{
switch (view.getId())
{
case R.id.constraint_layout_one:
case R.id.constraint_layout_two:
view.setOnTouchListener(new Gestures()
{
public boolean onSwipeTop()
{
showToast("swiped up");
return false;
}
public boolean onSwipeBottom()
{
showToast("swiped down");
return false;
}
});
}
return false;
}
#Override
public void onClick(View view)
{
if (view.getId() == R.id.constraint_layout_one)
{
showToast("button one clicked");
}
if (view.getId() == R.id.constraint_layout_two)
{
showToast("button two clicked");
}
}
public void showToast(String text)
{
Toast toast = Toast.makeText(getContext(), text, Toast.LENGTH_SHORT); // Generate toast message
toast.setGravity(Gravity.CENTER| Gravity.CENTER, 0, -1); // Change y-Position of toast a bit
toast.show(); // Show toast for 4 seconds
}
}
The two problems:
1)
When I start the app, the swipes don't work. Nothing happens when I swipe.
I have to perform 2 swipes to get it to work.
After that, I can swipe as often as I want.
2)
The clicks only work one time.
After the first click, no further clicks get recognized anymore (for the clicked view)
Same happens when I do two swipes - no clicks anymore.
Any help will be appreciated!
I tried something completely different. -> onInterceptTouchEvent
I created a helper class named RootView:
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.constraintlayout.widget.ConstraintLayout;
public class RootLayout extends ConstraintLayout
{
public RootLayout(Context context)
{
super(context);
}
public RootLayout(Context context, AttributeSet attributeSet)
{
super(context, attributeSet);
}
public RootLayout(Context context, AttributeSet attributeSet, int defStyleAttribute)
{
super(context, attributeSet, defStyleAttribute);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent motionEvent)
{
return true;
}
}
Inside of my xml file, I changed the ConstraintLayout to the RootLayout:
<com.example.testSwipeApp.RootLayout 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"
tools:layout_editor_absoluteY="81dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraint_layout_two"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#E91E63"
android:clickable="true"
android:focusable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_default="percent"
app:layout_constraintHeight_percent="0.4"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.3"
app:layout_constraintWidth_default="percent"
app:layout_constraintWidth_percent="1" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraint_layout_one"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#3F51B5"
android:clickable="false"
android:focusable="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_default="percent"
app:layout_constraintHeight_percent="0.5"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1"
app:layout_constraintWidth_default="percent"
app:layout_constraintWidth_percent="1" />
<TextView
android:id="#+id/text_view_header"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#000000"
android:gravity="center_horizontal"
android:paddingTop="2dp"
android:textColor="#ffffff"
android:textSize="15sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_default="percent"
app:layout_constraintHeight_percent="0.10"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</com.example.testSwipeApp.RootLayout>
The fragment1.java looks like this:
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
public class Fragment1 extends Fragment implements View.OnClickListener
{
ConstraintLayout constraintLayoutOne, constraintLayoutTwo;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View fragment1 = inflater.inflate(R.layout.fragment1, container, false); // Link view and layout
constraintLayoutOne = fragment1.findViewById(R.id.constraint_layout_one); // Link variable to ID
constraintLayoutTwo = fragment1.findViewById(R.id.constraint_layout_two); // Link variable to ID
fragment1.findViewById(R.id.constraint_layout_one).setOnClickListener(this);
fragment1.findViewById(R.id.constraint_layout_two).setOnClickListener(this);
fragment1.setOnTouchListener(new Gestures()
{
public boolean onSwipeTop()
{
Toast.makeText(getContext(), "Swiped up", Toast.LENGTH_SHORT).show();
return false;
}
public boolean onSwipeBottom()
{
Toast.makeText(getContext(), "Swiped down", Toast.LENGTH_SHORT).show();
return false;
}
});
return fragment1;
}
#Override
public void onClick(View view)
{
switch (view.getId())
{
case R.id.constraint_layout_one:
case R.id.constraint_layout_two:
showToast("clicked");
break;
}
}
public void showToast(String text)
{
Toast toast = Toast.makeText(getContext(), text, Toast.LENGTH_SHORT); // Generate toast message
toast.setGravity(Gravity.CENTER| Gravity.CENTER, 0, -1); // Change y-Position of toast a bit
toast.show(); // Show toast for 4 seconds
}
}
The problem:
Clicks don't get accepted anymore.
Even though this version works worse, I prefer this way rather than the old one.
Any help will be appreciated!
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;
}
}
}
I've looked through a few posts, but can't get the checkbox to acknowledge clicks. I think I'm 90% there but falling over the last hurdle.
I have a ListFragment where each item has a CheckBox and a TextView. When users click on the TextView they're taken to a new fragment. But when they click the CheckBox I want the value to be ticked/unticked directly in the list.
Here's my code, kept it so that only classes relevant to the ListView are shown, let me know if you need to see others.
I did follow this guide but can't really understand why it's not working on my code: http://www.mysamplecode.com/2012/07/android-listview-checkbox-example.html
TaskListFragment.java
package com.laytonlabs.android.todotoday;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
public class TaskListFragment extends ListFragment {
ArrayList<Task> mTasks;
private boolean mSubtitleVisible;
private Callbacks mCallbacks;
private static final String TAG = "TaskListFragment";
private int touchPositionX;
public interface Callbacks {
void onTaskSelected(Task task);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (Callbacks)activity;
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().setTitle(R.string.crimes_title);
mTasks = TaskLab.get(getActivity()).getTasks();
TaskAdapter adapter = new TaskAdapter(mTasks);
setListAdapter(adapter);
setRetainInstance(true);
mSubtitleVisible = false;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem showSubtitle = menu.findItem(R.id.menu_item_show_subtitle);
if (mSubtitleVisible && showSubtitle != null) {
showSubtitle.setTitle(R.string.hide_subtitle);
}
}
#TargetApi(11)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_new_crime:
Task task = new Task();
TaskLab.get(getActivity()).addTaskToFirst(task);
((TaskAdapter)getListAdapter()).notifyDataSetChanged();
mCallbacks.onTaskSelected(task);
return true;
case R.id.menu_item_show_subtitle:
if (getActivity().getActionBar().getSubtitle() == null) {
getActivity().getActionBar().setSubtitle(R.string.subtitle);
mSubtitleVisible = true;
item.setTitle(R.string.hide_subtitle);
} else {
getActivity().getActionBar().setSubtitle(null);
mSubtitleVisible = false;
item.setTitle(R.string.show_subtitle);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.crime_list_item_context, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
int position = info.position;
TaskAdapter adapter = (TaskAdapter)getListAdapter();
Task task = adapter.getItem(position);
switch (item.getItemId()) {
case R.id.menu_item_delete_crime:
TaskLab.get(getActivity()).deleteTask(task);
adapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
#TargetApi(11)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = super.onCreateView(inflater, parent, savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (mSubtitleVisible) {
getActivity().getActionBar().setSubtitle(R.string.subtitle);
}
}
ListView listView = (ListView)v.findViewById(android.R.id.list);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
//Use floating context menus on Froyo and Gingerbread
registerForContextMenu(listView);
} else {
//Use contextual action bar on Honeycomb and higher
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.crime_list_item_context, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_delete_crime:
TaskAdapter adapter = (TaskAdapter)getListAdapter();
TaskLab taskLab = TaskLab.get(getActivity());
for (int i = adapter.getCount() - 1; i >= 0; i--) {
if (getListView().isItemChecked(i)) {
taskLab.deleteTask(adapter.getItem(i));
}
}
mode.finish();
adapter.notifyDataSetChanged();
return true;
default:
return false;
}
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// TODO Auto-generated method stub
}
});
}
return v;
}
#Override
public void onResume() {
super.onResume();
((TaskAdapter)getListAdapter()).notifyDataSetChanged();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Task t = ((TaskAdapter)getListAdapter()).getItem(position);
mCallbacks.onTaskSelected(t);
}
private class TaskAdapter extends ArrayAdapter<Task> {
public TaskAdapter(ArrayList<Task> tasks) {
super(getActivity(), 0, tasks);
}
private class ViewHolder {
TextView titleTextView;
CheckBox completedCheckBox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
//If we wern't given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_task, null);
holder = new ViewHolder();
holder.titleTextView = (TextView)convertView.findViewById(R.id.task_list_item_titleTextView);
holder.completedCheckBox = (CheckBox)convertView.findViewById(R.id.task_list_item_completedCheckBox);
convertView.setTag(holder);
holder.completedCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Task task = (Task) cb.getTag();
task.setCompleted(cb.isChecked());
Log.d(TAG, "Clicked on checkbox for: " + task.getmTitle());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
//Configure the view for this Task
Task t = getItem(position);
holder.titleTextView.setText(t.getmTitle());
holder.completedCheckBox.setChecked(t.isCompleted());
holder.completedCheckBox.setTag(t);
return convertView;
}
}
public void updateUI() {
((TaskAdapter)getListAdapter()).notifyDataSetChanged();
}
}
list_item_task.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="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/task_list_item_completedCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:enabled="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="4dp" />
<TextView
android:id="#+id/task_list_item_titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:text="Task title" />
</LinearLayout>
Thanks in Advance!
Your clicks are not getting thru, because ur CheckBox has
android:enabled="false"
Which prevents the onClickListener from firing.
Remove this line, and try again.
Also, I advise you to change width of TextView to wrap_content, and rather position the CheckBox to the right.
In your list_item_task.xml layout file, where the CheckBox and TextView are defined, you set to the TextView
android:layout_width="match_parent"
when it should be as in the tutorial
android:layout_width="wrap_content"
It is possible that the too wide text is intercepting the click event from the checkbox.
For demonstration, I have a ListView displaying a list of numbers. I would like to achieve the effect that when the user scrolls the ListView and the scrolling ends, it will only stop at certain positions so that the first visible item is always shown completely. I've attached my attempted code below. It works when users drag to scroll the ListView. But when there's fling, the normal acceleration is interrupted, causing an unnatural stop. My question is, how can I take acceleration caused by fling into account while achieving the same effect?
package com.example.snaptest;
import android.content.Context;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private static class TestListViewAdapter extends BaseAdapter {
private Context mContext;
public TestListViewAdapter(Context context) {
mContext = context;
}
#Override
public int getCount() {
return 100;
}
#Override
public Object getItem(int position) {
return Integer.toString(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = new TextView(mContext);
textView.setText(Integer.toString(position));
AbsListView.LayoutParams params = new AbsListView.LayoutParams(ViewGroup.LayoutParams
.MATCH_PARENT, 180);
textView.setLayoutParams(params);
return textView;
}
}
private static class TestListView extends ListView {
public TestListView(Context context) {
super(context);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
View itemView = getChildAt(0);
int top = Math.abs(itemView.getTop()); // top is a negative value
int bottom = Math.abs(itemView.getBottom());
if (top >= bottom){
smoothScrollToPositionFromTop
(getFirstVisiblePosition() + 1, 0);
} else {
smoothScrollToPositionFromTop
(getFirstVisiblePosition(), 0);
}
}
return super.onTouchEvent(ev);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TestListView listView = new TestListView(this);
listView.setAdapter(new TestListViewAdapter(this));
setContentView(listView);
}
}
I would try with an OnScrollListener rather than extending ListView.
Something like this:
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.SCROLL_STATE_IDLE) {
// snap the listview according to the top/bottom items' visibility
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
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