hello guys I'm looking how to make my ListView clickable , i searched in the net but i haven't found the right answer , and this is my code please help me
`public class acceuil extends AppCompatActivity {
ListView listView;
int [] movie_poster_resource = {R.drawable.profil};
String[] patient_names;
String[] temps_rendez;
MovieAdapter adapter;
View view;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acceuil);
listView= (ListView)findViewById(R.id.listView);
temps_rendez = getResources().getStringArray(R.array.temps);
patient_names = getResources().getStringArray(R.array.patient_title);
int i=0;
adapter = new MovieAdapter(getApplicationContext(),R.layout.patient_name);
listView.setAdapter(adapter);
for (String titles: patient_names)
{
MovieDataProvider dataProvider = new MovieDataProvider(movie_poster_resource[i],titles,temps_rendez[i]);
adapter.add(dataProvider);
}
}
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
if (id == 0)
startActivity(new Intent(this, patient_from_listview.class));
}
public void open_messagerie (View view){
startActivity(new Intent(this, acceuil.class));
}
public void openn_otification (View view){
startActivity(new Intent(this, acceuil.class));
}
public void opena_parametre (View view){
startActivity(new Intent(this, acceuil.class));
}
public void open_calcule (View view){
startActivity(new Intent(this, acceuil.class));
}
}`
You'd call listView.setOnItemClickListener(OnItemClickListener). That sets the class to be called when an item is clicked. It looks like you've already implemented the onItemClicked function, this will hook it up.
This is how you can achieve this
adapter = new MovieAdapter(getApplicationContext(),R.layout.patient_name);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
// HERE YOU CAN MAKE CASES FOR EACH CLICK
}
Here is my code, how to do clickable listview on Android Studio...
MAIN ACTIVICTY CODE
ListView listView;
int mImage[] = {R.drawable.switzerland, R.drawable.canada, R.drawable.japan, R.drawable.usa};
String mTitle[] = {"Switzerland Title", "Canada Title", "Japan Title", "USA Title"};
String mDescription[] = {"Switzerland is a mountainous Central European country, home to numerous lakes, villages and the high peaks of the Alps.", "Canada is a country in the northern part of North America. Its ten provinces and three territories extend from the Atlantic to the Pacific.", "Japan is an island country in East Asia, located in the northwest Pacific Ocean.", "The U.S. is a country of 50 states covering a vast swath of North America, with Alaska in the northwest."};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// for listview settings
listView = findViewById(R.id.listview);
MyAdapter adapter = new MyAdapter(this, mImage, mTitle, mDescription);
listView.setAdapter(adapter);
//listview click listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (position==0){
Intent intent = new Intent(getApplicationContext(), Switzerland.class);
Bundle bundle = new Bundle();
bundle.putInt("image", mImage[0]);
intent.putExtras(bundle);
intent.putExtra("title", mTitle[0]);
intent.putExtra("description", mDescription[0]);
intent.putExtra("position", ""+0);
startActivity(intent);
}else if (position==1){
Intent intent = new Intent(getApplicationContext(), Canada.class);
Bundle bundle = new Bundle();
bundle.putInt("image", mImage[1]);
intent.putExtras(bundle);
intent.putExtra("title", mTitle[1]);
intent.putExtra("description", mDescription[1]);
intent.putExtra("position", ""+1);
startActivity(intent);
}else if (position==2){
Intent intent = new Intent(getApplicationContext(), Japan.class);
Bundle bundle = new Bundle();
bundle.putInt("image", mImage[2]);
intent.putExtras(bundle);
intent.putExtra("title", mTitle[2]);
intent.putExtra("description", mDescription[2]);
intent.putExtra("position", ""+2);
startActivity(intent);
}else if (position==3){
Intent intent = new Intent(getApplicationContext(), USA.class);
Bundle bundle = new Bundle();
bundle.putInt("image", mImage[3]);
intent.putExtras(bundle);
intent.putExtra("title", mTitle[3]);
intent.putExtra("description", mDescription[3]);
intent.putExtra("position", ""+3);
startActivity(intent);
}
}
});
}
// for listview adapter
class MyAdapter extends ArrayAdapter<String> {
Context context;
int sImage[];
String sTitle[];
String sDescription[];
MyAdapter (Context c, int image[], String title[], String description[]){
super(c, R.layout.main_page_row, R.id.main_page_title, title);
this.context = c;
this.sImage = image;
this.sTitle = title;
this.sDescription = description;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= layoutInflater.inflate(R.layout.main_page_row, parent, false);
ImageView imageView = view.findViewById(R.id.main_page_image);
TextView titleText = view.findViewById(R.id.main_page_title);
TextView descriptionText = view.findViewById(R.id.main_page_description);
imageView.setImageResource(sImage[position]);
titleText.setText(sTitle[position]);
descriptionText.setText(sDescription[position]);
return view;
}
}
Here is MAIN ACTIVITY XML Code
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="1500dp"
android:orientation="vertical">
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
Here is MAIN ACTIVITY ROW XML Code
<androidx.cardview.widget.CardView
android:orientation="vertical"
app:cardElevation="5dp"
app:cardCornerRadius="12dp"
android:layout_margin="3dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageID"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#drawable/erroricon"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/titleID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:text="#string/bb_name"
android:textSize="18sp"
android:textColor="#000000"
android:textStyle="bold" />
<TextView
android:id="#+id/descriptionID"
android:text="#string/mp_des"
android:layout_marginTop="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="10dp"
android:textColor="#000000"
android:textSize="16sp"
android:ellipsize="end"
android:maxLines="3"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
Here is Details Page Java Code
ImageView image;
TextView sTitle, sDescription;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details_page);
image = findViewById(R.id.details_page_image);
sTitle = findViewById(R.id.details_page_title);
sDescription = findViewById(R.id.details_page_description);
if (position == 0){
Intent intent = getIntent();
Bundle bundle = this.getIntent().getExtras();
int picture = bundle.getInt("image");
String postTitle = intent.getStringExtra("title");
String postDescrip = intent.getStringExtra("description");
image.setImageResource(picture);
sTitle.setText(postTitle);
sDescription.setText(postDescrip);
}
if (position == 1){
Intent intent = getIntent();
Bundle bundle = this.getIntent().getExtras();
int picture = bundle.getInt("image");
String postTitle = intent.getStringExtra("title");
String postDescrip = intent.getStringExtra("description");
image.setImageResource(picture);
sTitle.setText(postTitle);
sDescription.setText(postDescrip);
}
if (position == 2){
Intent intent = getIntent();
Bundle bundle = this.getIntent().getExtras();
int picture = bundle.getInt("image");
String postTitle = intent.getStringExtra("title");
String postDescrip = intent.getStringExtra("description");
image.setImageResource(picture);
sTitle.setText(postTitle);
sDescription.setText(postDescrip);
}
if (position == 3){
Intent intent = getIntent();
Bundle bundle = this.getIntent().getExtras();
int picture = bundle.getInt("image");
String postTitle = intent.getStringExtra("title");
String postDescrip = intent.getStringExtra("description");
image.setImageResource(picture);
sTitle.setText(postTitle);
sDescription.setText(postDescrip);
}
}
Related
I'm trying to set an OnItemClickListener with a custom adapter. The onItemClick is not firing when I press on.
I found that I need to add some attributes, but still doesn't work.
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
Activity:
public class StudentActivity {
private Activity mActivity;
private Student mStudent;
private TextView mName;
private Button mMonday;
private ListView mListView;
//That will be deleted
private ArrayList<HashMap<String, String>> list;
public StudentActivity(Activity activity, Student student) {
mActivity = activity;
mStudent = student;
mName = (TextView) mActivity.findViewById(R.id.name_student);
mName.setText(mStudent.getFirstName() + " " + mStudent.getLastName());
mListView = (ListView) mActivity.findViewById(R.id.list_view);
list = new ArrayList<>();
int numberOfIntervals = 7;
List<String> hours = new ArrayList<>();
hours.add("08:00-10:00");
hours.add("10:00-12:00");
hours.add("12:00-14:00");
hours.add("14:00-16:00");
hours.add("16:00-18:00");
hours.add("18:00-20:00");
hours.add("20:00-22:00");
for (int i = 0; i < numberOfIntervals; i++) {
HashMap<String, String> temp = new HashMap<>();
temp.put("First", hours.get(i));
temp.put("Second", "");
list.add(temp);
}
ListViewAdapter adapter = new ListViewAdapter(mActivity, list);
mListView.setAdapter(adapter);
addListenerForMondayButton(adapter);
addListenerForListViewItem(mListView);
}
private void addListenerForMondayButton(final ListViewAdapter adapter) {
mMonday = (Button) mActivity.findViewById(R.id.name_monday);
mMonday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ReservationTask reservationTask = new ReservationTask();
reservationTask.populateList(adapter);
}
});
}
private void addListenerForListViewItem(ListView view) {
view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
addNotification();
}
});
}
private void addNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(mActivity.getApplicationContext())
.setSmallIcon(R.drawable.arrow_back)
.setContentTitle("Notification")
.setContentText("This is a test notification");
Intent notificationIntent = new Intent(mActivity.getApplicationContext(), MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(mActivity.getApplicationContext(), 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager manager = (NotificationManager) mActivity.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
Adapter:
public class ListViewAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> mList;
private List<Reservation> mReservationList;
Activity mActivity;
TextView mHour;
TextView mName;
public ListViewAdapter(Activity activity, ArrayList<HashMap<String, String>> list) {
super();
mActivity = activity;
mList = list;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = mActivity.getLayoutInflater();
convertView=inflater.inflate(R.layout.list_view_item, null);
mHour = (TextView) convertView.findViewById(R.id.list_item_hour);
mName = (TextView) convertView.findViewById(R.id.list_item_name);
HashMap<String, String> map = mList.get(position);
mHour.setText(map.get("First"));
boolean set = false;
if (mReservationList != null && mReservationList.size() > 0) {
for (Reservation reservation: mReservationList) {
String createInterval = reservation.getStartHour() + "-" + reservation.getEndHour();
if (createInterval.equals(parseTime(mHour.getText().toString()))) {
mName.setText("Dima");
set = true;
}
}
if (set == false) {
mName.setText(map.get("Second"));
}
} else {
mName.setText(map.get("Second"));
}
return convertView;
}
public void populateNameReservation(List<Reservation> reservations) {
mReservationList = reservations;
notifyDataSetChanged();
}
private String parseTime(String intervalTime) {
String startHour = intervalTime.substring(0, intervalTime.indexOf("-"));
String endHour = intervalTime.substring(intervalTime.indexOf("-") + 1, intervalTime.length());
Time startHourTime = Time.valueOf(startHour + ":00");
Time endHourTime = Time.valueOf(endHour + ":00");
return startHourTime + "-" + endHourTime;
}
XML layout for list view:
<?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">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:text="Text View"
android:id="#+id/list_item_hour"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:text="Text View"
android:id="#+id/list_item_name"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
Thanks!!
Try this sample code i have used a list view with a custom class for inflating data in list view and then one clicking list item redirecting to another activity using intent.
Check this out it is working code.
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CustomList customList = new CustomList(TrainingProgrammes.this, listProgrms, reference_IDs, programStatus, _tierLevel, _tierIndexValue, programIDS);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(customList);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (programStatus.get(i).equals("Subscribed")) {
System.out.println("Program id is trianing programme new : " + programIDS.get(i) + " CLIENT_ID " + _clientID);
Intent nextScreen2 = new Intent(getApplicationContext(), TaskList.class);
nextScreen2.putExtra("EMAIL_ID", _loginID);
nextScreen2.putExtra("PROGRAMME_ID", programIDS.get(i));
nextScreen2.putExtra("CLIENT_ID", _clientID);
// nextScreen2.putExtra("PROGRAMME_STATUS", programStatus.get(i));
startActivity(nextScreen2);
}
}
});
}
Hope this helps you out.
Am developing an app that take student attendance, i want to get the list of checked the names on "TakeAttendance" when i click a "ViewAttendance" on same custom listview . Please how can i do that?
here is my codes...
The custom view
enter code here
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_firstname"
android:text="Firstname"
android:textSize="11dp"
android:ellipsize="start"
android:lines="3"
android:textColor="#000"
android:textStyle="bold"
android:gravity="center"
android:paddingLeft="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lastname"
android:lines="3"
android:textSize="11dp"
android:textColor="#000"
android:textStyle="bold"
android:gravity="center"
android:paddingLeft="10dp"
android:id="#+id/tv_lastname" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_surname"
android:text="Surname"
android:lines="3"
android:textSize="11sp"
android:textColor="#000"
android:textStyle="bold"
android:gravity="center"
android:paddingRight="80dp"
android:paddingLeft="10dp" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="20dp"
android:id="#+id/checkBox"
android:checked="false"
android:focusable="false"
android:background="#color/white" />
The Listview
enter code here
The ListAdapter
enter code herepublic class StudentListAdapter1 extends BaseAdapter {
private Context mContext;
private List mStudentList;
//Constructor
public StudentListAdapter1(Context mContext, List<StudentList> mStudentList) {
this.mContext = mContext;
this.mStudentList = mStudentList;
}
#Override
public int getCount() {
return mStudentList.size();
}
#Override
public Object getItem(int position) {
return mStudentList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = View.inflate(mContext, R.layout.student_take, null);
TextView tvReg_no = (TextView) v.findViewById(R.id.tv_reg_no);
TextView tvFirstname = (TextView) v.findViewById(R.id.tv_firstname);
TextView tvLastname = (TextView) v.findViewById(R.id.tv_lastname);
TextView tvSurname = (TextView) v.findViewById(R.id.tv_surname);
//Set text for TextView
tvReg_no.setText(mStudentList.get(position).getReg_no());
tvFirstname.setText(mStudentList.get(position).getFirstname());
tvLastname.setText(mStudentList.get(position).getLasttname());
tvSurname.setText(mStudentList.get(position).getSurname());
//Save product id to tag
v.setTag(mStudentList.get(position).getId());
return v;
}
}
The Attendance Activity
enter code here protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_take100);
lvStudentlist= (ListView) findViewById(R.id.listview_studentlist);
mStudentList = new ArrayList<>();
//Add sample data for list
//We can get data from DB, webservice here
mStudentList.add(new StudentList(1, "U11EE1001", "Bargo","S.","Mayafi"));
mStudentList.add(new StudentList(2, "U11EE1002", "Barnsbas","Snake.","Maciji"));
mStudentList.add(new StudentList(3, "U11EE1004", "Adamu","Tanko.","Sadau"));
mStudentList.add(new StudentList(4, "U11EE1005", "Munzali","","Cire Tallafi"));
//Init adapter
adapter = new StudentListAdapter1(getApplicationContext(), mStudentList);
lvStudentlist.setAdapter(adapter);
checkBox = (CheckBox) findViewById(R.id.checkBox);
lvStudentlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Do something
SparseBooleanArray checked = lvStudentlist.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<>();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
position = checked.keyAt(i);
// Add names if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
selectedItems.add((String) adapter.getItem(position));
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
Intent intent = new Intent(getApplicationContext(),
ViewAttendanceActivity.class);
// Create a bundle object
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
// Add the bundle to the intent.
intent.putExtras(b);
// start the ResultActivity
startActivity(intent);
}
});
}
}
The View Attendance Activity
enter code here protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_attendance);
Bundle b = getIntent().getExtras();
String[] resultArr = b.getStringArray("selectedItems");
lvStudentlist= (ListView) findViewById(R.id.listview_studentlist);
adapter = new StudentListAdapter(getApplicationContext(), mStudentList);
lvStudentlist.setAdapter(adapter);
}
}
At first I think you should reuse your items in listview
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView != null) {
v = convertView;
} else {
v = View.inflate(mContext, R.layout.student_take, null);
}
.......
now answer for your question, I think you need to add your selected items to array in lvStudentlist.setOnItemClickListener method and then send it as Intent extra to your next activity. You can send String[] as Intent extra so you have no need to use Bundle.
I am at my wits end trying to find a solution to this problem. I am unable to make OnItemClickListener work with my listview. While an analogous code is working perfectly fine with gridview. Here is my code.
public class Songs extends ListFragment implements /*AdapterView.OnItemClickListener,*/ LoaderManager.LoaderCallbacks<Cursor> {
SongsAdapter nAdapter;
private static final String ARG_POSITION = "position";
private int position;
public static Songs newInstance(int position) {
Songs f = new Songs();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View myFragmentView = inflater.inflate(R.layout.songs, container, false);
nAdapter = new SongsAdapter(getActivity(), null);
setListAdapter(nAdapter);
/* listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
});*/
return myFragmentView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(0, null, this);
//ListView listView = (ListView) getActivity().findViewById(android.R.id.list);
//ListView listView = (ListView) getActivity().findViewById(android.R.id.list);
FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab);
fab.attachToListView(getListView());
//getListView().setOnItemClickListener(this);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Toast.makeText(getActivity(), "Clicked " + position, Toast.LENGTH_SHORT).show();
}
/*
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT).show();
// startActivity(new Intent(getActivity(), MusicPlayer.class).putExtra("position", position).putExtra("orderby", orderby).putExtra("selection", selection).putExtra("val", val));
}
*/
I have tried everything including implementing OnItemClickListener to overriding OnListItemClick. But absolutely nothing seems to work.
Here is the layout of the fragment
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:id="#+id/content_frame"
android:layout_height="match_parent"
android:background="#color/metalList">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#drawable/listdivider"
android:dividerHeight="0.5dp"
android:layout_gravity="right|top"
android:clickable="false"
android:focusable="false"
android:fadeScrollbars="true"
android:fastScrollEnabled="true"
android:scrollbarStyle="insideInset"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:listSelector="#drawable/songlist_selector"/>
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_marginRight="26dp"
android:layout_marginBottom="16dp"
android:src="#drawable/shuffle_48"
fab:fab_colorNormal="#color/mm1"
fab:fab_colorPressed="#color/mm2"
fab:fab_shadow="true"
/>
</FrameLayout>
Try this
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "Item clicked", Toast.LENGTH_SHORT).show();
}
});
hope it works :)
Your OnItemClickListener() like below
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int itm=arg0.getItemAtPosition(arg2);
switch (itm) {
case 0:
Toast.makeText(m_context, "Item clicked", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(getActivity(), SecondActivity.class);
startActivity(intent1);
break;
}
});
Click on search item inside edittext redirect on wrong activity, it doesn't open the activity associated with it. It opening other activities that are associated with other listitems but not that i am clicking one.
Here is my complete code:
public class Tabtwo extends Activity implements OnItemClickListener {
ListView listView;
TextView txt;
ArrayAdapter<String> adapter;
// Search EditText
EditText edtSearch;
// Array of strings storing country names
String[] countries = new String[] { "Admin Cost", "Affinity Diagram",
"Analyse", "Apprasal Costs", "Assessment of Stakeholders",
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] flags = new int[] { R.drawable.admin, R.drawable.affinity,
R.drawable.analysis, R.drawable.appraisal, R.drawable.assessment,
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabtwo);
// Each row in the list stores country name, currency and flag
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 4; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("txt", countries[i]);
hm.put("flag", Integer.toString(flags[i]));
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag", "txt" };
// Ids of views in listview_layout
int[] to = { R.id.flag, R.id.txt };
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
final SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = (ListView) findViewById(R.id.listview);
edtSearch = (EditText) findViewById(R.id.Search_box);
txt = (TextView) findViewById(R.id.txt);
listView.setOnItemClickListener(this);
// Setting the adapter to the listView
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
edtSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
if (position == 0) {
Intent int0 = new Intent(getApplicationContext(), Admincost.class);
startActivity(int0);
}
if (position == 1) {
Intent int1 = new Intent(getApplicationContext(), Affinity.class);
startActivity(int1);
}
if (position == 2) {
Intent int2 = new Intent(getApplicationContext(), Analyse.class);
startActivity(int2);
}
if (position == 3) {
Intent int3 = new Intent(getApplicationContext(),
ApprasalCosts.class);
startActivity(int3);
}
if (position == 4) {
Intent int1 = new Intent(getApplicationContext(), Assessment.class);
startActivity(int1);
} }
}
}
Here is my tabtwo xml file.
<?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:orientation="vertical" >
<EditText
android:id="#+id/Search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Search a Item from ListView"
android:inputType="textVisiblePassword" />
/>
<TextView
android:id="#+id/List_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="12dip"
android:textSize="17sp"
android:textStyle="bold" />
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-50dp" />
</LinearLayout>
Here is listview_layout.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="horizontal" >
<ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp" />
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="21dp" />
</LinearLayout>
Replace your onItemClick method with below and try.. Hope it works..
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
TextView tv = (TextView) arg1.findViewById(R.id.txt);
String str = tv.getText().toString().trim();
if (str.equals(countries[0])) {
Intent int0 = new Intent(Tabtwo.this, Admincost.class);
startActivity(int0);
}else if(str.equals(countries[1])) {
Intent int1 = new Intent(Tabtwo.this, Affinity.class);
startActivity(int1);
}else if(str.equals(countries[2])) {
Intent int2 = new Intent(Tabtwo.this, Analyse.class);
startActivity(int2);
}else if(str.equals(countries[3])) {
Intent int3 = new Intent(Tabtwo.this, ApprasalCosts.class);
startActivity(int3);
}else if(str.equals(countries[4])) {
Intent int1 = new Intent(Tabtwo.this, Assessment.class);
startActivity(int1);
}
}
Add this code to your TextView as well as to ImageView
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
and for ItemClick you can use the answer of Tamilan
I meet the same question with you. Try the following one:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
//(String) getListAdapter().getItem(position);
String city_id=map.get( (String) adapter.getItem(position) );
Toast.makeText(getApplicationContext(),city_id, Toast.LENGTH_SHORT).show();
Intent i=new Intent(MainActivity.this,DetailActivity.class);
i.putExtra("city_id",city_id);
startActivity(i);
}
});
I'm new in android.I'm using listview which contains images and textview.I want to add arrow icon in each row.Im trying but i cannot accomplish this.How could i do this? The code is below.Any help is highly appreciated.
CategoryActivity.java
public class CategoryActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.category1);
ImageView in1 = (ImageView) findViewById(R.id.glrrr1);
in1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(),ImageSwitcherA.class);
startActivityForResult(myIntent, 0);
}
});
ImageView in2 = (ImageView) findViewById(R.id.grid1);
in2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent1 = new Intent(view.getContext(),RingGridView.class);
startActivityForResult(myIntent1, 0);
}
});
ListView view = (ListView) findViewById(R.id.list);
//instance of custom adapter
view.setAdapter(new CustomImageListAapter(this));
view.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Intent i = new Intent(AndroidGridLayoutActivity.this,FullImageActivity.class);
//Bundle bundle = new Bundle();
// bundle.putInt("operation", position);
//i.putExtras(bundle);
//startActivity(i);
if(position ==0)
{
Intent ii = new Intent(CategoryActivity.this,Ring1Full.class);
//Bundle bundle = new Bundle();
//bundle.putInt("operation", position);
ii.putExtra("operation", position);
startActivity(ii);
}
if(position ==1)
{
Intent in = new Intent(CategoryActivity.this,Ring2Full.class);
//Bundle bundle = new Bundle();
// bundle.putInt("operation", position);
in.putExtra("operation", position);
startActivity(in);
}
if(position ==2)
{
Intent inn = new Intent(CategoryActivity.this,Ring3Full.class);
//Bundle bundle = new Bundle();
//bundle.putInt("operation", position);
inn.putExtra("operation", position);
startActivity(inn);
}
if(position ==3)
{
Intent innm = new Intent(CategoryActivity.this,Ring4Full.class);
//Bundle bundle = new Bundle();
//bundle.putInt("operation", position);
innm.putExtra("operation", position);
startActivity(innm);
}
if(position ==4)
{
Intent intt = new Intent(CategoryActivity.this,Ring5Full.class);
//Bundle bundle = new Bundle();
// bundle.putInt("operation", position);
intt.putExtra("operation", position);
startActivity(intt);
}
if(position ==5)
{
Intent intt5 = new Intent(CategoryActivity.this,Ring6Full.class);
//Bundle bundle = new Bundle();
//bundle.putInt("operation", position);
intt5.putExtra("operation", position);
startActivity(intt5);
}
if(position == 6)
{
Intent buset= new Intent(CategoryActivity.this,Ring7Full.class);
// Bundle bundle = new Bundle();
//bundle.putInt("operation", position);
buset.putExtra("operation", position);
startActivity(buset);
}
if(position == 7)
{
Intent buses= new Intent(CategoryActivity.this,Ring8Full.class);
//Bundle bundle = new Bundle();
//bundle.putInt("operation", position);
buses.putExtra("operation", position);
startActivity(buses);
}
if(position == 8)
{
Intent busez= new Intent(CategoryActivity.this,Ring9Full.class);
//Bundle bundle = new Bundle();
//bundle.putInt("operation", position);
busez.putExtra("operation", position);
startActivity(busez);
}
if(position == 9)
{
Intent buseh= new Intent(CategoryActivity.this,Ring10Full.class);
//Bundle bundle = new Bundle();
//bundle.putInt("operation", position);
buseh.putExtra("operation", position);
startActivity(buseh);
}
if(position == 10)
{
Intent busek1= new Intent(CategoryActivity.this,Ring11Full.class);
//Bundle bundle = new Bundle();
//bundle.putInt("operation", position);
busek1.putExtra("operation", position);
startActivity(busek1);
}
if(position == 11)
{
Intent busek2= new Intent(CategoryActivity.this,Ring12Full.class);
//Bundle bundle = new Bundle();
//bundle.putInt("operation", position);
busek2.putExtra("operation", position);
startActivity(busek2);
}
if(position == 12)
{
Intent busek3= new Intent(CategoryActivity.this,Ring13Full.class);
//Bundle bundle = new Bundle();
// bundle.putInt("operation", position);
busek3.putExtra("operation", position);
startActivity(busek3);
}
if(position == 13)
{
Intent busek4= new Intent(CategoryActivity.this,Ring14Full.class);
//Bundle bundle = new Bundle();
// bundle.putInt("operation", position);
busek4.putExtra("operation", position);
startActivity(busek4);
}
if(position == 14)
{
Intent busek5= new Intent(CategoryActivity.this,Ring16Full.class);
// Bundle bundle = new Bundle();
// bundle.putInt("operation", position);
busek5.putExtra("operation", position);
startActivity(busek5);
}
if(position == 15)
{
Intent busek6= new Intent(CategoryActivity.this,Ring16Full.class);
//Bundle bundle = new Bundle();
//bundle.putInt("operation", position);
busek6.putExtra("operation", position);
startActivity(busek6);
}
if(position == 16)
{
Intent busek7= new Intent(CategoryActivity.this,Ring17Full.class);
// Bundle bundle = new Bundle();
//bundle.putInt("operation", position);
busek7.putExtra("operation", position);
startActivity(busek7);
}
if(position == 17)
{
Intent busek8= new Intent(CategoryActivity.this,Ring18Full.class);
//Bundle bundle = new Bundle();
//bundle.putInt("operation", position);
busek8.putExtra("operation", position);
startActivity(busek8);
}
}
});}}
CustomImageListAapter.java
public class CustomImageListAapter extends BaseAdapter {
private int[] images = {
R.drawable.rrr1,
R.drawable.rrr2,
R.drawable.rrr3,
R.drawable.rrr4,
R.drawable.rrr5,
R.drawable.rrr6,
R.drawable.rrr7,
R.drawable.rrr8,
R.drawable.rrr18,
R.drawable.rrr10,
R.drawable.rrr11,
R.drawable.rrr12,
R.drawable.rrr13,
R.drawable.rrr14,
R.drawable.rrr15,
R.drawable.rrr16,
R.drawable.rrr17,
R.drawable.rrr18,
};
private String[] imageDesc = { "Diamond Ring", "Silver Ring",
"Gold Ring","Antique Ring","Pearl Ring","Beats Ring","Diamond Ring","Stone Ring","Antique Ring","Diamond Ring", "Silver Ring",
"Gold Ring","Antique Ring","Pearl Ring","Beats Ring","Diamond Ring","Stone Ring","Antique Ring"};
Context ctx = null;
public CustomImageListAapter(Context context) {
this.ctx = context;
}
public int getCount() {
return images.length;
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int arg0, View arg1, ViewGroup arg2) {
ImageView imgView = new ImageView(this.ctx);
imgView.setScaleType(ScaleType.FIT_CENTER);
imgView.setPadding(8, 8, 8, 8);
imgView.setImageResource(images[arg0]);
imgView.setAdjustViewBounds(Boolean.TRUE);
imgView.setContentDescription(imageDesc[arg0]);
imgView.setMaxHeight(200);
imgView.setMaxWidth(200);
TextView tv = new TextView(this.ctx);
tv.setText(imageDesc[arg0]);
tv.setMaxHeight(100);
tv.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
tv.setGravity(Gravity.CENTER);
LinearLayout layoutView = new LinearLayout(this.ctx);
layoutView.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(150, 150);
layoutView.addView(imgView, params1);
LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
layoutView.addView(tv, params2);
return layoutView;
}
}
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:id="#+id/background"
android:gravity="center_vertical"
android:orientation="vertical" >
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/list"
android:background="#drawable/bkg">
</ListView>
</LinearLayout>
LinearLayout layoutView = new LinearLayout(this.ctx);
layoutView.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(150, 150);
layoutView.addView(imgView, params1);
LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
150 ,LayoutParams.WRAP_CONTENT);
layoutView.addView(tv, params2);
ImageView i1= new ImageView(this.ctx);
i1.setImageResource(R.drawable.ic_launcher);
layoutView.addView(i1);
return layoutView;
try that one get view add one imageview to that layout(layoutView)
First you will have to define a custom layout for the row of the ListView. The following code has an ImageView on the left side and then the title and sub-title with an arrow icon on the right side.
ListRow.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="wrap_content"
android:orientation="horizontal"
android:padding="5sp" >
<!-- Left side Thumbnail image -->
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5sp"
android:layout_alignParentLeft="true"
android:background="#drawable/image_bg"
android:layout_marginRight="5sp">
<ImageView
android:id="#+id/list_image"
android:layout_width="50sp"
android:layout_height="50sp"
/>
</LinearLayout>
<!-- Title-->
<TextView
android:id="#+id/title_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:textStyle="bold"/>
<!-- Subtitle -->
<TextView
android:id="#+id/subtitle_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title_name"
android:layout_marginTop="2sp"
android:layout_toRightOf="#+id/thumbnail"
/>
<!-- Rightend Arrow -->
<ImageView android:contentDescription="#string/right_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/arrow"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
Now you will have to create a Custom Adapter for displaying your custom ListView which will inflate the ListRow.xml and display the data in your list. You can also visit the following link for creating your layout:-
android-custom-listview-with-image-and-text
Hope this helps. Thanks.