setOnItemClickListener not working - java

My Listview app gets its data and background color of itemview from custom adapter ListAdapter.class.i also need to set the currently selected list items value in a textview below listview,but the setOnItemClickListener in MAinActivity is not executing.pls help.
This is my list view app:
Layout image
MainActivity.java
public class MainActivity extends Activity {
private static ListAdapterclass adapter;
ListView lv;
TextView tv2;
private final String android_versions[]={
"Donut",
"Eclair",
"Froyo",
"Gingerbread",
"Honeycomb",
"Ice Cream Sandwich",
"Jelly Bean",
"KitKat",
"Lollipop",
"Marshmallow"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
lv = (ListView) findViewById(R.id.listView1);
tv2 = (TextView) findViewById(R.id.selected);
adapter = new ListAdapterclass(getApplicationContext(), android_versions);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "hiiiiiiiii", Toast.LENGTH_SHORT).show();
System.out.println("********************** INSIDE ONITEMCLICKLISTNER IN MAIN ACTIVITY ******************");
String ver_name = (lv.getItemAtPosition(i)).toString();
tv2 = (TextView) findViewById(R.id.selected);
tv2.setText(ver_name);
}
});
}
}
ListAdapter.class
public class ListAdapterclass extends ArrayAdapter implements AdapterView.OnItemClickListener{
private String android_versionNames[];
Context mContext;
public int row_index=-1;
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int i, long l) {
int position=(Integer)v.getTag();
String ver_name=getItem(position).toString();
}
private static class ViewHolder{
TextView tv;
LinearLayout LL;
TextView tv2;
}
public ListAdapterclass(Context context,String android_versionnames[]) {
super(context, R.layout.list_item,android_versionnames);
this.android_versionNames=android_versionnames;
this.mContext=context;
System.out.println(" ???????????????????????? Inside dataadapter,Android names : ?????????????????????????????\n ");
for(int i=0;i<android_versionnames.length;i++){
System.out.println("\n"+android_versionnames[i]);
}
}
private int lastPosition=-1;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
String ver_name=getItem(position).toString();
final ViewHolder viewHolder;
final View result;
if(convertView==null){
viewHolder=new ViewHolder();
LayoutInflater inflater=LayoutInflater.from(getContext());
convertView=inflater.inflate(R.layout.list_item,parent,false);
viewHolder.tv=(TextView)convertView.findViewById(R.id.label);
viewHolder.LL=(LinearLayout) convertView.findViewById(R.id.linearLayout_1);
viewHolder.tv2=(TextView)convertView.findViewById(R.id.selected);
result=convertView;
convertView.setTag(viewHolder);
}else{
viewHolder=(ViewHolder) convertView.getTag();
result=convertView;
}
lastPosition=position;
viewHolder.tv.setText(ver_name);
viewHolder.LL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
row_index=position;
notifyDataSetChanged();
}
});
if(row_index==position){
viewHolder.LL.setBackgroundColor(Color.parseColor("#409de1"));
viewHolder.tv.setTextColor(Color.parseColor("#ffffff"));
}
else
{
viewHolder.LL.setBackgroundColor(Color.parseColor("#ffffff"));
viewHolder.tv.setTextColor(Color.parseColor("#000000"));
}
return convertView;
}
}
ActivityMain.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_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.cybraum.test.listviewcolorchange.MainActivity"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:clickable="true"
android:layout_weight="1"
>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView1"
>
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".2"
android:id="#+id/linearLayout_2"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Selected : "
android:textStyle="bold"
android:layout_gravity="center"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="text"
android:id="#+id/selected"
android:layout_gravity="center"/>
</LinearLayout>
</LinearLayout>
listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="#+id/linearLayout_1"
android:padding="10dp">
<TextView
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"
android:textColor="#000000"
android:gravity="center">
</TextView>
</LinearLayout>
what is the problem?

Remove viewHolder.LL.setOnClickListener listener from adapter and
In your adapter add a method to update row_index:
public void changeIndex(int rowIndex){
this.row_index = rowIndex;
notifyDataSetChanged();
}
Call this method from onItemClickListener event:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
adapter.changeIndex(i);//This will give you the same result of viewHolder.LL.setOnClickListener as you are doing
//Do whatever you are doing previously
}
});

If you take click event from adapter then listview itemclick could not work if you need adapter click event and listview item click please refer the link,
How to make imageView clickable from OnItemClickListener?
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long viewId = view.getId();
if (viewId == R.id.button1) {
Toast.makeText(this, "Button 1 clicked", Toast.LENGTH_SHORT).show();
} else if (viewId == R.id.button2) {
Toast.makeText(this, "Button 2 clicked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "ListView clicked" + id, Toast.LENGTH_SHORT).show();
}
}
In adapter:
viewHolder.Btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0); // Let the event be handled in onItemClick()
}

Use:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "hiiiiiiiii", Toast.LENGTH_SHORT).show();
System.out.println("********************** INSIDE ONITEMCLICKLISTNER IN MAIN ACTIVITY ******************");
String ver_name = (lv.getItemAtPosition(i)).toString();
tv2 = (TextView) findViewById(R.id.selected);
tv2.setText(ver_name);
}
});
And from adapter remove
implements AdapterView.OnItemClickListener

You need to remove your adaptor from the setOnClickListner()
Try to change Your method with
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Object o = prestListView.getItemAtPosition(position);
prestationEco str=(prestationEco)o;//As you are using Default String Adapter
Toast.makeText(getBaseContext(),str.getTitle(),Toast.LENGTH_SHORT).show();
}
});

change listview xml
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"></ListView>
remove AdapterView.OnItemClickListener from adapter class
public class ListAdapterclass extends ArrayAdapter {
}

change listview xml
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true">
</ListView>
remove AdapterView.OnItemClickListener from adapter class
public class ListAdapterclass extends ArrayAdapter {
}

Related

Listview Onclick Listener Not working after updating Cardview Layout

I have updated the layout, replaced the ImageViews with Buttons instaed, and the Listview OnCLick listener is not working now, when I used the old layout with ImageViews. Please let me know if this needs to be further formatted properly, any help will be approciated.
Listener in Activity:
lvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, ItemDetailsActivity.class);
intent.putExtra("Position", position);
startActivity(intent);
}
});
list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="#+id/ItemNametv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item : "
android:textSize="20sp"
android:layout_marginBottom="8dp"/>
<TextView
android:id="#+id/qtytv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Qty : "
android:layout_marginBottom="8dp"/>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_marginBottom="8dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/EditItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edit"
android:minWidth="0dp"
android:minHeight="0dp"
style="#style/Widget.AppCompat.Button.Borderless"/>
<Button
android:id="#+id/DeleteItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:textColor="#color/btn_logut_bg"
android:minWidth="0dp"
android:minHeight="0dp"
style="#style/Widget.AppCompat.Button.Borderless"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
ItemDetailsAdapter.java:
public class ItemDetailsAdapter extends BaseAdapter {
private ArrayList<Item> arrayListItem;
private Context context;
private LayoutInflater inflater;
public ItemDetailsAdapter(Context context, ArrayList<Item> arrayListItem) {
this.context = context;
this.arrayListItem = arrayListItem;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayListItem.size();
}
#Override
public Object getItem(int position) {
return arrayListItem.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
Holder holder;
if (v == null) {
v = inflater.inflate(R.layout.list_item, null);
holder = new Holder();
holder.ItemName = (TextView) v.findViewById(R.id.ItemNametv);
holder.qty = (TextView) v.findViewById(R.id.qtytv);
holder.EditItem = (Button) v.findViewById(R.id.EditItem);
holder.DeleteItem = (Button) v.findViewById(R.id.DeleteItem);
v.setTag(holder);
}
else {
holder = (Holder) v.getTag();
}
holder.ItemName.setText(arrayListItem.get(position).getItem());
holder.qty.setText(arrayListItem.get(position).getQty());
holder.EditItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,AddOrUpdateItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("Position", position);
context.getApplicationContext().startActivity(intent);
}
});
holder.DeleteItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShowConfirmDialog(context, position);
}
});
return v;
}
class Holder {
TextView ItemName, qty;
Button DeleteItem, EditItem;
}
public static void ShowConfirmDialog(Context context, final int position) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder
.setMessage("Are you sure you want to delete this entry?")
.setCancelable(true)
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.getInstance().deleteItem(position);
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
There is issue of views getting in conflict i.e. views might be getting over lapped by others so add
android:descendantFocusability="blocksDescendants" on your parent layout and list item and for all views for which you want to handle click events, for them, android:focusable="false" add this as well like here in button...
TRY this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent">
Step 1: In list_item.xml, add android:descendantFocusability="blocksDescendants" to your root Linearlayout.
Step 2: In list_item.xml, add android: focusable="false" to android.support.v7.widget.CardView
Note: If there is android:clickable="true" in android.support.v7.widget.CardView remove it.

Listview and button hidden

Well, I try to explain.
I made an application where I have a listview where each row have also two buttons (I have made it with other question posted in this site).
The problem is this:
The two buttons is "start" and "stop". When I click start, a service starts and when I click on stop this service has to stop (I haven't implemented the service for now).
So, when I click start, I would like to hide the start button, in this way I know that the service is started.
How can I do it? Besides, it can be the right choice implements the service in this way?
I have choosen this idea because I need to stop the service when I decide to stop it.
Code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
android.widget.ListAdapter adapter = new ListAdapter(this,0,list);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.list_item);
lView.setAdapter(adapter);
}
}
activity_main.xml:
<?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.sara.myapplication.MainActivity">
<ListView
android:id="#+id/list_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
row_item.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">
<TextView
android:text="Text"
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5pt"
android:layout_marginTop="2pt"
android:textSize="10pt"
android:layout_weight="0.49"/>
<Button
android:text="Start"
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="Stop"
android:id="#+id/stop_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/start_button"/>
</LinearLayout>
ListAdapter.java
public class ListAdapter extends ArrayAdapter<String> {
private ArrayList<String> list;
private int layout;
private Context context;
public ListAdapter(Context context, int resource, ArrayList<String> objects) {
super(context, resource, objects);
context = context;
layout = resource;
list = objects;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
view = inflater.inflate(R.layout.row_item, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.stop_button);
Button addBtn = (Button)view.findViewById(R.id.start_button);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "delete - Button was clicked for list item " + position, Toast.LENGTH_SHORT).show();
//do something
notifyDataSetChanged();
}
});
addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "start - Button was clicked for list item " + position, Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
});
return view;
}
}
you can use some boolean flag value to change the visibility of button on click.
addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "start - Button was clicked for list item " + position, Toast.LENGTH_SHORT).show();
//do something
addBtn.setVisibility(View.GONE);
notifyDataSetChanged();
}
});
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "delete - Button was clicked for list item " + position, Toast.LENGTH_SHORT).show();
//do something
addBtn.setVisibility(View.VISIBLE);
notifyDataSetChanged();
}
});
In this way seems working
If on your list you have more than one element, then you have to implement a custom adapter and create an ad hoc listner for each element. Use setTag and getTag.
CHange row_item.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">
<TextView
android:text="Text"
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5pt"
android:layout_marginTop="2pt"
android:textSize="10pt"
android:layout_weight="0.49"/>
<Button
android:text="Start"
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="start"/>
<Button
android:text="Stop"
android:id="#+id/stop_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/start_button"
android:onClick="stop"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/start_button" />
</LinearLayout>
And in MainAcitivty
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
ListAdapter adapter = new ListAdapter(this, 0, list);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.list_item);
lView.setAdapter(adapter);
}
public void start(View v){
Button b = (Button) v;
v.setVisibility(View.INVISIBLE);
}
public void stop(View v){
}
}
ListAdapter
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
view = inflater.inflate(R.layout.row_item, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.stop_button);
Button addBtn = (Button)view.findViewById(R.id.start_button);
return view;
}
You need to use the setVisible(false) method
Example:
addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "start - Button was clicked for list item " + position, Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
addBtn.setVisible(false); // ← Hide the "Start button"
}
});
To Hide start Button after clicking,
addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "start - Button was clicked for list item " + position, Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
addBtn.setVisibility(View.GONE);
}
});

Ghosting Effect: Two views on top of each other. Why?

I want to be able to click on buttons to navigate forward and backward through several views as well as swiping left or right between views.
So I decided to implement the ViewPager for swiping between multiple views.
Here's my code:
layout xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"/>
<ImageView
android:id="#+id/apple"
android:layout_width="200sp"
android:layout_height="150sp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/apple"
android:contentDescription="apple"/>
<TextView
android:id="#+id/number"
android:layout_width="100sp"
android:layout_height="55sp"
android:layout_marginTop="47dp"
android:layout_below="#+id/apple" android:layout_alignStart="#+id/apple"/>
<Button
android:id="#+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/save"
android:layout_alignTop="#+id/ignore" android:layout_toStartOf="#+id/apple"/>
<Button
android:id="#+id/ignore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Ignore"
android:layout_alignParentBottom="true" android:layout_toEndOf="#+id/apple"/>
<ImageView
android:id="#+id/back_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_back"
android:contentDescription="back">
</ImageView>
<ImageView
android:id="#+id/forward_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_forward"
android:layout_alignParentTop="true" android:layout_alignParentEnd="true"
android:contentDescription="forward">
</ImageView>
</RelativeLayout>
Here's my activity:
public class CollectionPager extends Activity {
private PagerAdapter pagerAdapter;
ActionBar actionbar;
MyAdapter myAdapter;
private Context context;
private TextView textView;
private int currentPage;
ViewPager viewPager;
int progressChanged = 0;
public static final String TAG = "CollectionPager";
public CollectionPager() {
context = this;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.collection);
viewPager = (ViewPager) findViewById(R.id.viewPager);
myAdapter = new MyAdapter();
viewPager.setAdapter(myAdapter);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.hide();
}
//Initialize the back button and add an onClick event listener to the button
final ImageView back_button = (ImageView) findViewById(R.id.back_nav_arrow);
back_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//it doesn't matter if you're already in the first item
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
});
//Initialize the forward button and add an onClick event listener to the button
final ImageView forward_button = (ImageView) findViewById(R.id.forward_nav_arrow);
forward_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//it doesn't matter if you're already in the last item
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
});
final Button save_button = (Button) findViewById(R.id.save);
save_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//save
}
});
final Button ignore_button = (Button) findViewById(R.id.ignore);
ignore_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//ignore
}
});
//Attach the page change listener inside the activity
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
//This method will be invoked when a new page becomes selected
#Override
public void onPageSelected(int position) {
//get position
currentPage = position;
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int i) {
//get state
}
});
}
private class MyAdapter extends PagerAdapter {
int NumberOfPages = 10;
LayoutInflater inflater = (LayoutInflater) CollectionPager.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public int getCount() {
return NumberOfPages;
}
#Override
public Object instantiateItem(ViewGroup parent, int position) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.collection, parent, false);
ImageView imageView = (ImageView) view
.findViewById(R.id.apple);
imageView.setImageResource(R.drawable.apple);
parent.addView(view,0);
return view;
}
#Override
public void destroyItem(ViewGroup parent, int position, Object object) {
((ViewPager) parent).removeView((View) object);
}
#Override
public boolean isViewFromObject(View parent, Object object) {
return parent== ((View) object);
}
#Override
public Parcelable saveState() {
return null;
}
}
}
The onClickEvent is detected but here's a screenshot on what is happening to the view. Two view on top of each other. One view is fixed on the screen and the other one is scrolling correctly.
I'm not sure why this happens. What is causing this to occur in my code?
EDIT: Here's a video highlighting the issue: https://www.dropbox.com/s/6x5qa16xyttzrwa/VIDEO0041.mp4?dl=0
Change
#Override
public boolean isViewFromObject(View parent, Object object) {
return parent== ((View) object);
}
to
#Override
public boolean isViewFromObject(View v, Object o) {
return parent == object;
}
Update:
After watching your movie your problem is you put some static wedget on the top of your viewpager, so remove that, which means your layout will become something like this:
This is your main_activity.xml you must assign it to your activity by function setContentView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"/>
</RelativeLayout>
then at instantiateItem use below layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
>
<ImageView
android:id="#+id/apple"
android:layout_width="200sp"
android:layout_height="150sp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/apple"
android:contentDescription="apple"/>
<TextView
android:id="#+id/number"
android:layout_width="100sp"
android:layout_height="55sp"
android:layout_marginTop="47dp"
android:layout_below="#+id/apple" android:layout_alignStart="#+id/apple"/>
<Button
android:id="#+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/save"
android:layout_alignTop="#+id/ignore" android:layout_toStartOf="#+id/apple"/>
<Button
android:id="#+id/ignore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Ignore"
android:layout_alignParentBottom="true" android:layout_toEndOf="#+id/apple"/>
<ImageView
android:id="#+id/back_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_back"
android:contentDescription="back">
</ImageView>
<ImageView
android:id="#+id/forward_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_forward"
android:layout_alignParentTop="true" android:layout_alignParentEnd="true"
android:contentDescription="forward">
</ImageView>
your main activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.collection);
viewPager = (ViewPager) findViewById(R.id.viewPager);
myAdapter = new MyAdapter();
viewPager.setAdapter(myAdapter);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.hide();
}
//Attach the page change listener inside the activity
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
//This method will be invoked when a new page becomes selected
#Override
public void onPageSelected(int position) {
//get position
currentPage = position;
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int i) {
//get state
}
});
}
then assign your click listener of your main activity at this function
#Override
public Object instantiateItem(ViewGroup parent, int position) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.collection, parent, false);
ImageView imageView = (ImageView) view
.findViewById(R.id.apple);
imageView.setImageResource(R.drawable.apple);
final ImageView back_button = (ImageView) view.findViewById(R.id.back_nav_arrow);
back_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//it doesn't matter if you're already in the first item
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
});
parent.addView(view,0);
return view;
}

Long click doesn't work with ListView

I'm trying to set long-click listener for ListView:
final ListView gallery=(ListView)findViewById(R.id.dialogViewImagesList);
gallery.setLongClickable(true);
gallery.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
Log.e("event", "long");
return true;
}
});
gallery.setAdapter(new PointImagesAdapter(bitmaps));
It's my adapter:
private class PointImagesAdapter extends ArrayAdapter<Bitmap> {
private static final int LAYOUT_ID=R.layout.adapter_point_images;
private List<Bitmap> bitmaps;
private LayoutInflater inflater;
public PointImagesAdapter(List<Bitmap> bitmaps) {
super(MainActivity.this, LAYOUT_ID, bitmaps);
this.bitmaps=bitmaps;
inflater=LayoutInflater.from(MainActivity.this);
}
#Override
public View getView(int position, View view, ViewGroup group) {
if (view==null) {
view=inflater.inflate(LAYOUT_ID, null);
}
ImageView i=(ImageView)view.findViewById(R.id.adapterPointImagesItem);
i.setScaleType(ImageView.ScaleType.CENTER);
i.setImageBitmap(bitmaps.get(position));
view.setFocusable(false);
return view;
}
}
I've tried set view.setLongClickable(true), but in this case ListView items are not clickable (simple click doesn't work). It's layout code for adapter:
<?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:focusable="false"
android:orientation="vertical" >
<ImageView
android:focusable="false"
android:layout_gravity="center"
android:layout_marginTop="5dip"
android:id="#+id/adapterPointImagesItem"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
I don't understand why this code doesn't work! How can I fix it?
You have to use setOnItemLongClickListener
gallery.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
});
}
Also, If your listview's adapter extends from BaseAdapter, then you also need to set convertView.setLongClickable(true); in the getView().

How to replace fragment run time

I want to add and replace Frame layout with fragment on fragment-1 and fragment-2 on item click of Grid and List item.
I had created main.xml class
<?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="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:layout_height="fill_parent" >
<fragment
android:id="#+id/fragment1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
class="com.example.fragment.Fragment1" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#000000" />
<fragment
android:id="#+id/fragment2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
class="com.example.fragment.Fragment2" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="fill_parent"
android:background="#000000" />
<FrameLayout
android:id="#+id/fragment3"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="2"/>
Here is my fragment_1.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"
android:paddingLeft="8dp"
android:paddingRight="8dp" >
<GridView
android:id="#+id/Grid1"
android:layout_width="match_parent"
android:numColumns="auto_fit"
android:columnWidth="100dp"
android:layout_height="0dp"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
and here is my row_fragment1_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="15dp"
android:orientation="vertical" >
<ImageView
android:id="#+id/img_view"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#CCCCCC"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp" />
and fragment_3.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:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_fragment3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="22sp"
android:gravity="center"
android:text="This is 3rd Fragment" />
and here is my Main.xml
public class Main extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
and here is Fragment1.class
public class Fragment1 extends Fragment implements OnItemClickListener
{
Activity myActivity;
GridView mGridView;
private String ListItem[] = {"Item 1","Item 2","Item 3","Item 4","Item 5","Item 6","Item 7"};
private int imgID[] = {R.drawable.admin_access_rule,
R.drawable.admin_backup,R.drawable.admin_browsesite,
R.drawable.admin_comment_post,R.drawable.admin_content,
R.drawable.admin_content_type,R.drawable.admin_logout,};
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
this.myActivity = activity;
Toast.makeText(activity.getApplicationContext(), "On Attach", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Toast.makeText(myActivity.getApplicationContext(), "On Create", Toast.LENGTH_SHORT).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Create View", Toast.LENGTH_SHORT).show();
View view = inflater.inflate(R.layout.fragment_1,container, false);
mGridView = (GridView)view.findViewById(R.id.Grid1);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Activity Created", Toast.LENGTH_SHORT).show();
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart()
{
super.onStart();
mGridView.setAdapter(new GridBaseAdapter(myActivity));
mGridView.setOnItemClickListener(this);
}
private class GridBaseAdapter extends BaseAdapter
{
LayoutInflater mLayoutInflater = null;
public GridBaseAdapter(Context mContext)
{
mContext = myActivity;
mLayoutInflater = LayoutInflater.from(mContext);
}
#Override
public int getCount()
{
return ListItem.length;
}
#Override
public Object getItem(int position)
{
return null;
}
#Override
public long getItemId(int position)
{
return ListItem.length;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
if(convertView == null)
{
convertView = mLayoutInflater.inflate(R.layout.row_fragment_list, null);
}
ImageView mImageView = (ImageView) convertView.findViewById(R.id.img_view);
mImageView.setImageResource(imgID[position]);
TextView tvUserEmail = (TextView) convertView.findViewById(R.id.text2);
tvUserEmail.setText("Sub " +ListItem[position]);
return convertView;
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
TextView txt3 = (TextView)myActivity.findViewById(R.id.tv_fragment3);
txt3.setText("1st Fragment's : " + position +" Item Clicked");
}
}
My Fragment2.class
public class Fragment2 extends ListFragment
{
Activity myActivity;
private String ListItem[] = {"Item 1","Item 2","Item 3","Item 4","Item 5","Item 6","Item 6","Item 7"};
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
this.myActivity = activity;
Toast.makeText(activity.getApplicationContext(), "On Attach", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Toast.makeText(myActivity.getApplicationContext(), "On Create", Toast.LENGTH_SHORT).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Create View", Toast.LENGTH_SHORT).show();
/** Creating an array adapter to store the list of countries **/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1,ListItem);
/** Setting the list adapter for the ListFragment */
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Activity Created", Toast.LENGTH_SHORT).show();
super.onActivityCreated(savedInstanceState);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
Toast.makeText(myActivity.getApplicationContext(), position +" Item Clicked", Toast.LENGTH_SHORT).show();
TextView txt3 = (TextView)myActivity.findViewById(R.id.tv_fragment3);
txt3.setText("2nd Fragment's : " + position +" Item Clicked");
super.onListItemClick(l, v, position, id);
}
}
And Last my Fragment3.class
public class Fragment3 extends Fragment
{
Activity myActivity;
TextView txt_view;
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
this.myActivity = activity;
Toast.makeText(activity.getApplicationContext(), "On Attach", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Toast.makeText(myActivity.getApplicationContext(), "On Create", Toast.LENGTH_SHORT).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Create View", Toast.LENGTH_SHORT).show();
View view = inflater.inflate(R.layout.fragment_3,container, false);
txt_view = (TextView)view.findViewById(R.id.tv_fragment3);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Activity Created", Toast.LENGTH_SHORT).show();
super.onActivityCreated(savedInstanceState);
}
}
Make fragments expose interface that your activity can attach itself to. The event should occur when desired (e.g. list item is clicked). Then, activity should place instance of the fragment where it should be, for example:
// fragment is an instance of the fragment you want to show
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment3, fragment);
transaction.commit();

Categories