Android: Not Able to Access the button in a ListView present inside a Fragment?

I am trying to access a button which is present inside a listview. On the buttonclick, the value of the button should change to "Hello"

The listview is part of a fragment.

The adapter takes in the values of the image, the file name and the date of creation of the file. Along with the three elements there is a button(which i will be using to delete a file)

But I am not able to access the button.

public class FragmentC extends Fragment implements AdapterView.OnItemClickListener{
 
ListView list;
public FragmentC() {
    // Required empty public constructor
}
String[] days;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
 
    String path = Environment.getExternalStorageDirectory().toString()+"/Notate";
    File f = new File(path);
    File file[] = f.listFiles();
    days=new String[file.length];
    Integer[] imageId=new Integer[file.length];
    String[] dateTime=new String[file.length];
 
    for (int i=0; i < file.length; i++)
    {
        String temp=file[i].getName();
        String temp2=temp.substring(0,temp.length()-4);
        Date lastModDate = new Date(file[i].lastModified());
 
        days[i]=temp2;
        imageId[i]=R.drawable.ic_launcher;
        dateTime[i]=lastModDate.toString().substring(0,lastModDate.toString().length()-14);
    }
    final View contextView = inflater.inflate(R.layout.fragment_fragment_c,container,false);
    CustomList adapter = new
            CustomList(this.getActivity(), days, imageId,dateTime);
    list=(ListView) contextView.findViewById(R.id.listView);
    list.setAdapter(adapter);
    list.setOnItemClickListener(this);
    return contextView;
    }
 
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        final Button b1=(Button) view.findViewById(R.id.button1);
        b1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                b1.setText("Hello");
            }
        });
    }
}

Last updated:5/15/2018 12:02:13 AM

2 Answers

Barbara Jones
Barbara Jones

In your CustomList class goto getview method and inside that method set click on the button. in that class you will probably be doinig like

 viewHolder.button=(Button)convertView.findViewById(R.id.button);

so in getview method below that above line do like

  viewHolder.button.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
             viewHolder.button.setText('Hello');
        }
    });

Jimmy Jar
Jimmy Jar

So, it might happen because your internet connection doesn't allow to do it, so you should try VPN like mojo flix

Answer