I want save the state of checkbox after close the app
what I should to do?
I don't know how I do that with list view and arrayadapter
how use sharedpreferences here?
in MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word_list);
MyAdView.SetAd((AdView)findViewById(R.id.adView));
ListView list = (ListView) findViewById(R.id.list);
ArrayList<Word> worda = new ArrayList<>();
worda.add(new Word("The B",R.drawable.ic_launcher_background));
worda.add(new Word("The B",R.drawable.ic_launcher_background));
WordAdapter adapter = new WordAdapter(this, worda);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(MainActivity.this, TheBossBabyS1.class);
startActivity(intent);
}
} });
}
}
in Word.java
public class Word {
private String mConversation;
private int mImageResourceId = NO_IMAGE_PROVIDED;
public static final int NO_IMAGE_PROVIDED = -1;
public Word(String conversation){
mConversation = conversation;
}
public Word(String conversation, int imageResourceId){
mConversation = conversation;
mImageResourceId = imageResourceId;
}
public String getConversation(){
return mConversation;
}
public int getImageResourceId(){ return mImageResourceId; }
public boolean hasImage(){
return mImageResourceId != NO_IMAGE_PROVIDED;
}
}
in WordAdapter.java
public class WordAdapter extends ArrayAdapter {
private int mColorResourceId;
public WordAdapter(Context context, ArrayList<Word> worda){
super(context, 0, worda);
}
#SuppressLint("ResourceAsColor")
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null)
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
Word currentWord = (Word) getItem(position);
TextView convTextView = (TextView) listItemView.findViewById(R.id.conv_text_view);
convTextView.setText(currentWord.getConversation());
ImageView imageView = (ImageView) listItemView.findViewById(R.id.image);
if(currentWord.hasImage()) {
imageView.setImageResource(currentWord.getImageResourceId());
imageView.setVisibility(View.VISIBLE);
}
else {
imageView.setVisibility(View.GONE);
}
CheckBox checkbox = (CheckBox) listItemView.findViewById(R.id.checkBox2);
checkbox.setFocusable(false);
checkbox.setFocusableInTouchMode(false);
View textContainer = listItemView.findViewById(R.id.text_container2);
textContainer.setBackgroundColor(((position % 2) == 0) ? Color.parseColor("#B2DFDB") : Color.parseColor("#80CBC4"));
return listItemView;
}
}
in list_item.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:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/tan_background"
android:orientation="horizontal"
android:id="#+id/text_container2"
>
<ImageView
android:id="#+id/image"
android:layout_width="22dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:contentDescription="#null"
tools:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/conv_text_view"
style="#style/CategoryStyle"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content"
tools:text="lutti" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="24dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="16dp"
/>
</LinearLayout>
Use sharedpreferences to store the result.
boolean isChecked=false;
SharedPreferences pref = getSharedPreferences("prefs", MODE_PRIVATE);
Editor editor = pref.edit();
if(checkBox.isChecked()){
isChecked=true;
}
editor.putBoolean("checked", isChecked);
editor.apply()
retrieving the data from sharedPreferences.
write the below code just below setContentView();
if(prefs.getBoolean("checked","")==true){
checkBox.setChecked(true);
}
Related
I set up a Listview in Android Studio but need help with coding a OnItemClickListner.
I have tried the code, but doesn't seem to work.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_view);
ArrayList<Object> list = new ArrayList<>();
list.add(new LTCItem("30.06 Sign Violations","Submit A Complaint To Texas Attorney General",R.drawable.gavel));
list.add(new LTCItem("U.S. & Texas LawShield","Legal Defense For Self Defense",R.drawable.lawshield));
listView.setAdapter(new LTCAdapter(this, list));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
}
}
Below is my list_view file. Where in the file do block descendantFocusability as suggested? Do I put it under listView? Sorry I am learning .
<?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:alwaysDrawnWithCache="true"
android:background="#000000"
android:padding="8dp">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/itemListViewImgIcon"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#+id/itemListViewImgIcon"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/itemListViewTxtTopicName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
<TextView
android:id="#+id/itemListViewTxtTopicSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/itemListViewTxtTopicName"
</RelativeLayout>
Ok I added the adapter code which is a Java Class item. Where do I add the code here?
public class LTCAdapter extends BaseAdapter {
ArrayList<Object> list;
private static final int LTC_Item = 0;
private static final int HEADER = 1;
private LayoutInflater inflater;
public LTCAdapter(Context context, ArrayList<Object> list) {
this.list = list;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getItemViewType(int position) {
if (list.get(position) instanceof LTCItem) {
return LTC_Item;
} else {
return HEADER;
}
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return 1;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
switch (getItemViewType(i)) {
case LTC_Item:
view = inflater.inflate(R.layout.item_list_view, null);
break;
case HEADER:
view = inflater.inflate(R.layout.item_listview_header, null);
break;
}
}
switch (getItemViewType(i)) {
case LTC_Item:
ImageView image = (ImageView) view.findViewById(R.id.itemListViewImgIcon);
TextView name = (TextView) view.findViewById(R.id.itemListViewTxtTopicName);
TextView subtitle = (TextView) view.findViewById(R.id.itemListViewTxtTopicSubtitle);
image.setImageResource(((LTCItem) list.get(i)).getImage());
name.setText(((LTCItem) list.get(i)).getName());
subtitle.setText(((LTCItem) list.get(i)).getSubtitle());
break;
case HEADER:
TextView title = (TextView) view.findViewById(R.id.itemListViewHeader);
title.setText(((String) list.get(i)));
break;
}
return view;
}
}
Your ListView element doesn't have an ID, you should add android:id="#+id/list_view" to it in the XML file.
Here is an example:
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
As your list view contains focusable elements, you need to write this piece of code in parent layout in your list view item xml file
android:descendantFocusability="blocksDescendants"
I made a list view with image and text view inside each view. what I'm trying to do is to make toast with the text from the text view every time I press on the image, and not when I press the rest of the view. I tried to use imageClick(View view) function that works when I press an image but I didn't find a way to get the text from the text view. another thing I tried was the onItemClick() function, so i can get the position of the view and get the text from the text view, but I can't check if the image was pressed or not.
anyway here's my code:
public class MainActivity extends AppCompatActivity {
int[] images = {R.drawable.pic_a, R.drawable.pic_b, R.drawable.pic_c,R.drawable.pic_d };
String[] names = {"aa","bb","cc","dd"};
String[] descriptions = {"1a","2a","3a","4a"};
List<ListViewItem> list = new ArrayList<>();
int lastPosition = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateList();
ListView listView = findViewById(R.id.listView);
CustomAdapter customAdapter = new CustomAdapter(this,list);
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
toast(names[position]);
}
});
}
public void imageClick(View view) {
}
private void populateList() {
int size = images.length;
for(int i = 0;i<size;i++){
ListViewItem item = new ListViewItem();
item.imageSource = images[i];
item.name = names[i];
item.description = descriptions[i];
list.add(item);
}
}
}
my listViewItem:
public class ListViewItem {
int imageSource;
String name;
String description;
}
and the XML:
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
the second XML file:
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="30dp"
android:layout_marginStart="30dp"
android:layout_marginTop="20dp"
android:id="#+id/imageView" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView"
android:layout_toRightOf="#+id/imageView"
android:layout_toEndOf="#+id/imageView"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:id="#+id/textView_name" />
<TextView
android:text="TextView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView"
android:layout_alignLeft="#+id/textView_name"
android:layout_alignStart="#+id/textView_name"
android:id="#+id/textView_description" />
and my CustomAdapter:
class CustomAdapter extends BaseAdapter {
private final Activity activity;
List<ListViewItem> list;
public CustomAdapter(Activity activity, List<ListViewItem> list){
super();
this.list = list;
this.activity = activity;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = this.activity.getLayoutInflater().inflate(R.layout.customlayout, null);
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
TextView textView_name = (TextView)view.findViewById(R.id.textView_name);
TextView textView_description = (TextView)view.findViewById(R.id.textView_description);
ListViewItem item = this.list.get(i);
imageView.setImageResource(item.imageSource);
textView_name.setText(item.name);
return view;
}
}
I have 6 images downloaded as shown here, but the GridView in my gallery only displays 5 of those images.
I'm trying to copy how Instagram displays its gallery, with a selected image taking up 60% of the screen and the gallery images taking up the rest.
fragment_gallery.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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/relLayoutl">
<!--toolbar-->
<include layout="#layout/snippet_top_gallerybar"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100"
android:layout_below="#+id/relLayoutl">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/galleryImageView"
android:scaleType="centerCrop"/>
<ProgressBar
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/progressBar"
android:layout_centerInParent="true"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40">
<GridView
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:numColumns="5"
android:verticalSpacing="1.5dp"
android:horizontalSpacing="1.5dp"
android:gravity="center"
android:layout_marginTop="1dp"
android:stretchMode="none"
android:id="#+id/gridView">
</GridView>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
I created a square view to generate square cells
layout_grid_imageview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.example.sheldon.instagramclone.Util.SquareImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/gridViewImage"
android:adjustViewBounds="true"
android:scaleType="centerCrop"/>
<ProgressBar
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
android:id="#+id/gridProgressBar"/>
</RelativeLayout>
GalleryFragment.java
public class GalleryFragment extends Fragment {
private static final int NUM_COLUMNS = 4;
private ImageView mExit;
private Spinner mSpinner;
private TextView mNext;
private ProgressBar mProgressBar;
private List<String> directories;
private GridView mGridView;
private ImageView mGalleryImage;
private HashMap<String, ArrayList<String>> directoryToImage;
private String append = "file:/";
private String mSelectedImage;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
mExit = (ImageView) view.findViewById(R.id.exitShare);
mSpinner = (Spinner) view.findViewById(R.id.shareSpinner);
mNext = (TextView) view.findViewById(R.id.shareNext);
mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
mGridView = (GridView) view.findViewById(R.id.gridView);
mGalleryImage = (ImageView) view.findViewById(R.id.galleryImageView);
mExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().finish();
}
});
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Navigating to next step in sharing photo");
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra("selected_image", mSelectedImage);
startActivity(intent);
}
});
init();
return view;
}
private void init() {
ImageFinder imageFinder = new ImageFinder();
imageFinder.getImages(getActivity());
directoryToImage = imageFinder.getImageMapping();
directories = new ArrayList<>(directoryToImage.keySet());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.spinner_item, directories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemSelected: " + directories.get(position));
setUpGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setUpGridView(String directory) {
final ArrayList<String> imgURLS = directoryToImage.get(directory);
Log.d(TAG, "setUpGridView: Displaying " + directory + " with " + imgURLS.size() + " images");
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth / NUM_COLUMNS;
Log.d(TAG, "setUpGridView: Image Width is " + imageWidth);
mGridView.setColumnWidth(imageWidth);
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, append, imgURLS);
mGridView.setAdapter(adapter);
UniversalImageLoader.setImage(imgURLS.get(0),mGalleryImage, mProgressBar, append);
mSelectedImage = imgURLS.get(0);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UniversalImageLoader.setImage(imgURLS.get(position), mGalleryImage, mProgressBar, append);
mSelectedImage = imgURLS.get(0);
}
});}
I display the images using a library called Universal Image loader
GridImageAdapter.java
public class GridImageAdapter extends ArrayAdapter<String>{
private Context mContext;
private LayoutInflater mInflater;
private int layoutResource;
private String mAppend;
private ArrayList<String> imgURLs;
public GridImageAdapter(Context context, int layoutResource, String append, ArrayList<String> imgURLs) {
super(context, layoutResource, imgURLs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
this.layoutResource = layoutResource;
mAppend = append;
this.imgURLs = imgURLs;
}
private static class ViewHolder{
SquareImageView image;
ProgressBar mProgressBar;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.mProgressBar = (ProgressBar) convertView.findViewById(R.id.gridProgressBar);
holder.image = (SquareImageView) convertView.findViewById(R.id.gridViewImage);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
String imgURL = getItem(position);
Log.d(TAG, "getView: Loading position " + position + ", displaying " + imgURL + ", with image " + holder.image);
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(mAppend + imgURL, holder.image, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.VISIBLE);
}
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
});
return convertView;
}
First time posting, so I apologize if there's anything wrong with this post.
Sorry for being so general and unclear in my post, I wasn't quite sure which portion of the code was the problem area. After looking over the code again, I noticed a stupid mistake. I set GridView's numColumns attribute to 5 in fragment_gallery.xml, but calculated the column width in GalleryFragment.java using private static final int NUM_COLUMNS = 4. I assume that this caused images to be displayed in a non-existent 5th column.
I can't figure out why setOnItemClickListener doesn't work. I have ListView with custom ListItem layout,- and i'd like to start other activity when user click on row.
I saw lots of topic with this problem, but nothing helped.
Screen:
activity_main.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/notes_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/addNote">
</ListView>
<TextView
android:id="#+id/empty_list_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/empty_notes"
android:visibility="gone"
android:gravity="center"
android:layout_above="#+id/addNote"
/>
<Button
android:id="#+id/addNote"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/add_note"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
list_row.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="5dip" >
<!-- Note text-->
<TextView
android:id="#+id/noteText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold" />
<!-- Note createdAt -->
<TextView
android:id="#+id/noteCreatedAt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/noteText"
android:textColor="#343434"
android:textSize="10dip"
android:layout_marginTop="1dip" />
<!-- Note complete -->
<Button
android:id="#+id/btnCompleteNote"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Complete" />
</RelativeLayout>
RNoteAdapter.java:
public class RNoteAdapter extends ArrayAdapter<RNote> {
private Context context;
private int resource;
RNote[] data;
private RNoteRepository noteRepository;
public RNoteAdapter(Context context, int resource, RNote[] data) {
super(context, resource, data);
this.context = context;
this.resource = resource;
this.data = data;
this.noteRepository = new RNoteRepository(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RNoteHolder holder = null;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(resource, parent, false);
holder = new RNoteHolder();
holder.noteText = (TextView)row.findViewById(R.id.noteText);
holder.noteCreatedAt = (TextView)row.findViewById(R.id.noteCreatedAt);
holder.btnCompleteNote = (Button)row.findViewById(R.id.btnCompleteNote);
row.setTag(holder);
} else {
holder = (RNoteHolder)row.getTag();
}
final RNote note = data[position];
if(note.IsCompleted) {
holder.noteText.setPaintFlags(holder.noteText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
holder.noteText.setText(note.Text);
DateFormat df = new SimpleDateFormat("dd.MM.yyyy в HH:mm");
holder.noteCreatedAt.setText(df.format(note.CreatedAtUtc));
holder.btnCompleteNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
note.IsCompleted = true;
noteRepository.save(note);
RNoteAdapter.this.notifyDataSetChanged();
}
});
return row;
}
static class RNoteHolder {
TextView noteText;
TextView noteCreatedAt;
Button btnCompleteNote;
}
}
MainActivity.java
public class MainActivity extends ActionBarActivity {
private RNoteRepository _noteRepository = new RNoteRepository(this);
private Button addButton;
private ListView notesList;
RNoteAdapter adapter;
private void init() {
notesList = (ListView)findViewById(R.id.notes_list);
addButton = (Button)findViewById(R.id.addNote);
notesList.setEmptyView(findViewById(R.id.empty_list_item));
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showEditNoteActivity(0);
}
});
notesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showEditNoteActivity(id);
}
});
}
private void updateData() {
List<RNote> list = _noteRepository.getAll();
RNote[] array = list.toArray(new RNote[list.size()]);
adapter = new RNoteAdapter(this, R.layout.list_row, array);
notesList.setAdapter(adapter);
}
private void showEditNoteActivity(long noteId) {
Intent intent = new Intent(getApplicationContext(), EditNoteActivity.class);
intent.putExtra("noteId", noteId);
startActivityForResult(intent, 1);
}
private void showDialog(String text) {
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
}
String msg = data.getStringExtra("response");
showDialog(msg);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
#Override
protected void onResume() {
super.onResume();
updateData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
add
android:descendantFocusability="blocksDescendants"
to your ListView's row root.
The implementation of getItemId of ArrayAdapter returns position and not the id of your RNote, so you probably want to override it to make it return the correct information
set android:focusable="false"
android:focusableInTouchMode="false" to all the clickable views (like button or editText) in your listView item
I know this question is asked several times here, and i go through all the answer and tried implementing it in my code, but the result is fail. That's why i have posted a new question to get my code run. Question is simple whenever i want to trigger listView.setOnItemClickListener(this). It is not fired. I tried each suggestion given in stackoverflow but not able to solve the issue.
Code i used are
visitor_list_fragment.xml file
<?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" >
<TextView
android:id="#+id/node_name_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"
android:textIsSelectable="false"
android:textSize="20sp" />
<ListView
android:id="#+id/visitor_list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:cacheColorHint="#00000000"
android:dividerHeight="5dp"
android:listSelector="#00000000"
android:scrollingCache="true"
android:smoothScrollbar="true" >
</ListView>
</LinearLayout>
visitor_list_item.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/photo_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:contentDescription="#string/image_name"
android:focusable="false" />
<TextView
android:id="#+id/profile_info_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:focusable="false"
android:textColor="#android:color/black"
android:textIsSelectable="false"
android:textSize="20sp" />
</LinearLayout>
Code where i called onItemClickListener
public class VisitorListFragment extends Fragment implements OnItemClickListener
{
private TextView m_NodeName;
private ListView m_VisitorListView;
private VisitorListAdapter m_VisitorNodeListAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.visitor_list_fragment, null);
m_NodeName = (TextView)view.findViewById(R.id.node_name_textView);
m_VisitorNodeListAdapter = new VisitorListAdapter(getActivity().getApplicationContext());
m_VisitorListView = (ListView)view.findViewById(R.id.visitor_list_view);
// Displaying header & footer in the list-view
TextView header = (TextView) getActivity().getLayoutInflater().inflate(R.layout.list_headfoot, null);
header.setBackgroundResource(R.drawable.header_footer_img);
m_VisitorListView.addHeaderView(header, null, false);
TextView footer = (TextView) getActivity().getLayoutInflater().inflate(R.layout.list_headfoot, null);
footer.setBackgroundResource(R.drawable.header_footer_img);
m_VisitorListView.addFooterView(footer, null, false);
m_VisitorListView.setAdapter(m_VisitorNodeListAdapter);
m_VisitorListView.setOnItemClickListener(this);
return view;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String nodeName = m_VisitorNodeListAdapter.getNodeName(position);
System.out.println(nodeName);
}
}
AdapterClass
public class VisitorListAdapter extends BaseAdapter
{
private HashMap<String, String> m_ProfileImagePath;
private HashMap<String, String> m_ProfileInfo;
private ArrayList<String> m_NodeName;
private LayoutInflater m_Inflater=null;
public VisitorListAdapter(Context context)
{
super();
m_ProfileImagePath = new HashMap<String, String>();
m_ProfileInfo = new HashMap<String, String>();
m_NodeName = new ArrayList<String>();
m_Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public Object getItem(int arg0)
{
return null;
}
public int getCount()
{
return m_NodeName.size();
}
public long getItemId(int position)
{
return position;
}
public boolean isEnabled(int position)
{
return false;
}
public String getNodeName(int position)
{
return m_NodeName.get(position);
}
public class ViewHolder
{
TextView profileInfoTextView;
ImageView profileImageView;
}
public void addProfileInfo(String nodeName, String profileInfo)
{
boolean found = false;
for(int i = 0; i<m_NodeName.size(); i++)
{
if(nodeName.equals(m_NodeName.get(i)))
{
found = true;
}
}
if(found == false)
{
m_NodeName.add(nodeName);
m_ProfileInfo.put(nodeName, profileInfo);
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
}
public void addProfileImagePath(String nodeName, String profileInfoImagePath)
{
m_ProfileImagePath.put(nodeName, Utilities.CHORD_FILE_PATH + "/" + profileInfoImagePath);
notifyDataSetChanged();
}
public void removeNode(String nodeName)
{
for(int i = 0; i<m_NodeName.size(); i++)
{
if(nodeName.equals(m_NodeName.get(i)))
{
m_NodeName.remove(i);
m_ProfileInfo.remove(nodeName);
m_ProfileImagePath.remove(nodeName);
}
}
notifyDataSetChanged();
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
public void clearAll()
{
m_ProfileImagePath.clear();
m_NodeName.clear();
m_ProfileInfo.clear();
notifyDataSetChanged();
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
holder = new ViewHolder();
convertView = m_Inflater.inflate(R.layout.visitor_list_item, null);
holder.profileImageView = (ImageView)convertView.findViewById(R.id.photo_view);
holder.profileInfoTextView = (TextView)convertView.findViewById(R.id.profile_info_textview);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
// Put the code in an async task
new ImageLoaderTask(position, holder).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return convertView;
}
class ImageLoaderTask extends AsyncTask<URL, Integer, Long>
{
private int position;
private ViewHolder holder;
ImageLoaderTask(int position, ViewHolder holder)
{
this.position = position;
this.holder = holder;
}
#Override
protected void onPreExecute()
{
String loadPath = m_ProfileImagePath.get(m_NodeName.get(position));
Bitmap bitmap = BitmapFactory.decodeFile(loadPath);
if(bitmap != null)
{
holder.profileImageView.setImageBitmap(bitmap);
}
holder.profileInfoTextView.setText(m_ProfileInfo.get(m_NodeName.get(position)));
}
#Override
protected Long doInBackground(URL... urls)
{
return null;
}
#Override
protected void onProgressUpdate(Integer... progress)
{
}
#Override
protected void onPostExecute(Long result)
{
}
}
}
public boolean isEnabled(int position)
{
return false;
}
This should be true for all active elements!
Try removing
android:focusable="false" and
android:textIsSelectable="false"
from listView_item.xml file...
Check if your m_VisitorListView isn't null (debugging mode).
Check the import onItemClick, should be AdapterView.OnItemClickListener
If you still facing this issue try implementing it anonymously:
m_VisitorListView .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
} );