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);
}
});
Related
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 {
}
Basically I have listview in my fragment layout. And another layout called item_todo.xml which contains my button.
The onClick() wasn't working while clicking the delete_task button in my layout.
It would be great if you could help me out !
Here is my Class ToDoFragment
public class ToDoFragment extends Fragment {
private static final String TAG = "MainActivity";
private TaskDbHelper mHelper;
private ListView mTaskListView;
private ArrayAdapter<String> mAdapter;
Button myButton;
FloatingActionButton btnadd;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
mHelper = new TaskDbHelper(getActivity());
mTaskListView = (ListView) view.findViewById(R.id.list_todo);
//Floating action button
btnadd = (FloatingActionButton) view.findViewById(R.id.btnadd);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText taskEditText = new EditText(getActivity());
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle("Add a new task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
null,
values,
SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
});
updateUI();
return view;
}
#Override
public void onActivityCreated(Bundle saved){
super.onActivityCreated(saved);
final LayoutInflater factory = getActivity().getLayoutInflater();
final View textEntryView = factory.inflate(R.layout.item_todo, null);
myButton = (Button) textEntryView.findViewById(R.id.task_delete);
myButton.setOnClickListener(new View.OnClickListener() {
// OnClick() Not Working !!
#Override
public void onClick(View view) {
deleteTask(view);
}
});
}
public void deleteTask(View view) {
View parent = (View) view.getParent();
TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
String task = String.valueOf(taskTextView.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(TaskContract.TaskEntry.TABLE,
TaskContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{task});
db.close();
updateUI();
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(TaskContract.TaskEntry.TABLE,
new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(getActivity(),
R.layout.item_todo,
R.id.task_title,
taskList);
mTaskListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}}
Fragment_two XML
<ListView
android:id="#+id/list_todo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:orientation="horizontal" >
<android.support.design.widget.FloatingActionButton
android:layout_width="50dp"
android:id="#+id/btnadd"
android:layout_height="50dp"
app:fabSize="normal"
android:clickable="true"
android:src="#drawable/red"
android:scaleType="center"
/>
</LinearLayout>
</RelativeLayout>
item_todo 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"
android:layout_gravity="center_vertical">
<TextView
android:id="#+id/task_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="Hello"
android:textSize="20sp" />
<Button
android:id="#+id/task_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:text="Done" />
</RelativeLayout>
You inflate a new View in your onActivityCreated But you never used that view !!! myButton refer to a button which its view has not been used !
Edit :
There are lots of ways you can reach your goal:
Interfaces
You can initialize an interface and pass it to fragment, so whenever something happen in your activity (button click for example), you will understand
BroadcastReceivers
You can register local broadcast receivers in your fragment and when user click on the button, you send that broadcast, so fragment will understand
i suggest the second one and using EVENTBUS library
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;
}
I'm looking for a way to implement a dialog which asks for confirmation when clicking on the delete button of my ListView row. I tried to do it inside my custom ArrayAdapter, but as it is no Activity I don't know how to do it.
When I put the whole onClick-Listener inside the MainActivity, I have no clou how to find out which position the button was clicked so that I can remove it afterwards.
public class ServiceAdapter extends ArrayAdapter<Service> {
private final Singleton singleton = Singleton.getInstance();
private ArrayList<Service> services;
public ServiceAdapter(Context context, ArrayList<Service> services) {
super(context, 0, services);
this.services = services;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Service service = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.listview_row, parent, false);
}
// Lookup view for data population
TextView quantity = (TextView) convertView
.findViewById(R.id.QUANTITY_CELL);
TextView description = (TextView) convertView
.findViewById(R.id.DESCRIPTION_CELL);
Button delete = (Button) convertView.findViewById(R.id.BUTTON_DELETE);
// Populate the data into the template view using the data object
quantity.setText(String.valueOf(service.getQuantity()));
description.setText(service.getDescription());
// Set up the listener for the delete button.
final View view = convertView;
view.setTag(Integer.valueOf(position));
delete.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer) view.getTag();
services.remove(index.intValue());
notifyDataSetChanged();
}
});
// Return the completed view to render on screen
return convertView;
}
}
public class MainActivity extends Activity {
private ListView serviceList;
private ArrayList<Service> services;
private ServiceAdapter adapter;
private final Singleton singleton = Singleton.getInstance();
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serviceList = (ListView) findViewById(R.id.service_list);
adapter = new ServiceAdapter(this, services);
serviceList.setAdapter(adapter);
serviceList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
Service temp = services.get(position);
singleton.setQuantity(temp.getQuantity());
singleton.setDescription(temp.getDescription());
setPosition(position);
openDetailedEntry();
}
});
}
public void openDetailedEntry() {
Intent i = new Intent(this, DetailedEntryActivity.class);
// Check if the meant Activity is actually resolvable
if (i.resolveActivity(getPackageManager()) != null)
startActivity(i);
}
}
<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="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<TableLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:paddingTop="8dp"
>
<ListView
android:id="#+id/service_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="2dp" />
</TableLayout>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listview_row"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="4dip"
android:paddingBottom="4dip"
android:paddingLeft="4dip"
android:paddingRight="4dip"
android:orientation="horizontal">
<TextView android:id="#+id/QUANTITY_CELL"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textSize="20sp"
/>
<TextView android:id="#+id/DESCRIPTION_CELL"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_weight="6" />
<Button
android:id="#+id/BUTTON_DELETE"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:textSize="12sp"
android:focusable="false"
android:text="#string/delete" />
</LinearLayout>
Let me know if you need something.
Construct AlertDialog in ServiceAdapter Like this,
private AlertDialog mDialog;
private int mListRowPosition;
public ServiceAdapter(Context context, ArrayList<Service> services) {
super(context, 0, services);
this.services = services;
//Create AlertDialog here
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Your Message")
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Use mListRowPosition for clicked list row...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object
mDialog = builder.create();
}
Create method in ServiceAdapter Like,
private void showDialog(int position)
{
mListRowPosition = position;
if(mDialog != null)
mDialog.show();
}
Now in onClick() Just call
showDialog(position); // But make position of getView() as final...
how to select row item using Tick mark like iphone in android?iam using imageview in list_row.xml.when i click the list row item then i show image in row imageview.
if(getItem(position)!=null){
img.setvisibilty(View.Visible);}
else{System.out.println("imagenull");}
iam using this but image display in last row only.please help me how to select item using tickmark image.
public class DistanceArrayAdapter extends ArrayAdapter<Constant>{
public static String category,state,miles;
public ImageView img;
private Context context;
private int current = -1;
ArrayList<Constant> dataObject;
public DistanceArrayAdapter(Context context, int textViewResourceId,
ArrayList<Constant> dataObject) {
super(context, textViewResourceId, dataObject);
this.context=context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView=convertView;
if(rowView==null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.category_row, parent, false);
}
//TextView textView = (TextView) rowView.findViewById(R.id.text1);
TextView textView1 = (TextView) rowView.findViewById(R.id.text2);
//textView.setText(""+getItem(position).id);
textView1.setText(""+getItem(position).caption);
img=(ImageView)rowView.findViewById(R.id.img);
img.setVisibility(View.GONE);
if(position%2==1)
{
rowView.setBackgroundResource(R.color.even_list);
}
else
{
rowView.setBackgroundResource(R.color.odd_list);
}
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(img.getVisibility()==View.GONE)
{
img.setVisibility(View.VISIBLE);
System.out.println("1");
}
if(img.getVisibility()==View.VISIBLE){
img.setVisibility(View.GONE);
System.out.println("12");
}
miles=getItem(position).caption;
System.out.println("miles"+miles);
}
});
return rowView;
}
}
Drawing from https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
String[] GENRES = new String[] {"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"};
private CheckBoxAdapter mCheckBoxAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.lv);
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
listView.setAdapter(mCheckBoxAdapter);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuilder result = new StringBuilder();
for (int i = 0; i < GENRES.length; i++) {
if (mCheckBoxAdapter.mCheckStates.get(i) == true) {
result.append(GENRES[i]);
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 1000).show();
}
});
}
public void onItemClick(AdapterView parent, View view, int position, long id) {
mCheckBoxAdapter.toggle(position);
}
class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener {
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
String[] gen;
private SparseBooleanArray mCheckStates;
private SparseBooleanArray mCheckStates;
CheckBoxAdapter(MainActivity context, String[] genres) {
super(context, 0, genres);
mCheckStates = new SparseBooleanArray(genres.length);
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gen = genres;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return gen.length;
}
}
}
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
And the XML file for the checkboxes:
<?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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="34dp"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:layout_marginRight="22dp"
android:layout_marginTop="23dp" />
</RelativeLayout>
When you click the button a toast message with list of item choosen is displayed. You can modify the above according to your requirements.
Set selection mode on your ListView
//if using ListActivity or ListFragment
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//or
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//myListView is reference to your ListView
1.Make visibility gone to you tick mark image
2.Implement view.setOnClickListener in arrayadapter.
3.In that check image.getVisibility()==View.GONE then make image.setVisibity(View.Visible)
4.if image.getVisiblity()==View.VISIBLE then make your image.setVisibity(View.GONE)
Try this.