ListView Click in android fragment - android

I can't move from fragment to Activity on ListItem Click Listener i think i am doing it right but don't know where is problem.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
return inflater.inflate(R.layout.scholorship_listing_main,container,false);
}
#Override
public void onStart() {
super.onStart();
list=(ListView)getActivity().findViewById(R.id.Scholorshiplist);
setAdapterValue();
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), ScholorshipDetail.class);
getActivity().startActivity(intent);
//getActivity().finish();
}
});
}
And my Activity class on which I want to move is
public class ScholorshipDetail extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scholorship_detail);
}
}
and my xml is:
<?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"
tools:context="com.example.temp.scholorshipapp.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scholorships"
android:textColor="#color/black"
android:textSize="25sp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="80dp"
android:layout_centerHorizontal="true"
android:id="#+id/txt_scholorship"
android:divider="#C0C0C0"
android:dividerHeight="4px"/>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#android:color/black"
android:layout_below="#+id/txt_scholorship"/>
<ListView
android:layout_below="#id/txt_scholorship"
android:id="#+id/Scholorshiplist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#C0C0C0"
android:dividerHeight="4px"
/>
</RelativeLayout>

Post the code in onCreateview() instead of onStart() in your fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmentlayout, container, false);
list=(ListView) view.findViewById(R.id.Scholorshiplist);
setAdapterValue();
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), ScholorshipDetail.class);
getActivity().startActivity(intent);
//getActivity().finish();
}
});
return view;
}

This might be your adapter layout contains the click listener view.i.e, button view or some other view, which will block the listview click listner. So in your adapter parent layout you need add block descendent or focusability as below,
android:descendantFocusability="blocksDescendants"
(OR)
android:focusable="false"
Hope this is helpful:)

Related

Multiple Items Selected on ListView, selects wrong items

I have this code for a ListView on a Fragment. My goal is to select multiple items on the list and to highlight them. My code does highlight the item, but when I scroll the list, more items are highlighted and when I scroll up again, more items are highlighted again and it goes crazy over and over highlighting and changing to default state, whenever I scroll the list. I don't know why it happens.
NOTE: I've tried CHOICE_MODE_SINGLE, CHOICE_MODE_MULTIPLE, CHOICE_MODE_MULTIPLE_MODAL and I also tried MultiChoiceModeListener but my App should be working on API above 9. So that's not a solution for me.
My Fragment (Don't want to use ListFragment)
public class InventarioFragment extends Fragment {
ListView listInventario;
public static InventarioFragment newInstance()
{
return new InventarioFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_inventario_list,container,false);
listInventario = (ListView) view.findViewById(R.id.list_inv);
listInventario.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
v.setBackgroundColor(Color.BLUE);
}
});
return view;
}
}
This is the XML of my Fragment (Notice that I am using an array for the items on the list).
My Fragment XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:orientation="horizontal"
android:weightSum="1">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5">
<ImageButton
android:id="#+id/ib_cancel_inventario"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/btn_cancel"
android:layout_centerInParent="true"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5">
<ImageButton
android:id="#+id/ib_submit_inventario"
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/btn_ok"
android:layout_centerInParent="true"/>
</RelativeLayout>
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="20dp"
android:background="#DF0101"/>
<ListView
android:id="#+id/list_inv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:entries="#array/list_inventario"
>
</ListView>
</LinearLayout>
</LinearLayout>
I'm not using and Adapter because I set the list items from a default array.
Sorry for my english, and I hope you can help me. (I can't upload images because I don't have enough reputation yet).
You can use the following adapter to achieve your goal.
Remove android:entries="#array/list_inventario" in your Listview and add choicemode as follows in your XML.
<ListView
android:id="#+id/list_inv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="multipleChoice">
</ListView>
InventarioFragment
public class InventarioFragment extends Fragment {
private Activity activity;
private ListView listInventario;
private String[] inventatioItems;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity=activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_inventario_list,container,false);
listInventario = (ListView) view.findViewById(R.id.list_inv);
inventatioItems=getResources().getStringArray(R.array.list_inventario);
InverntarioAdapter adapter=new InverntarioAdapter(activity);
listInventario.setAdapter(adapter);
listInventario.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int pos, long arg3) {
listInventario.setItemChecked(pos, true);;
}
});
return view;
}
private class InverntarioAdapter extends BaseAdapter{
private LayoutInflater inflator;
public InverntarioAdapter(Context context){
inflator=(LayoutInflater) context.getSystemService(activity.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return inventatioItems.length;
}
#Override
public Object getItem(int position) {
return inventatioItems[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TextView tv;
if(convertView == null){
convertView=inflator.inflate(android.R.layout.simple_list_item_1, null);
convertView.setBackground(getResources().getDrawable(R.drawable.selector_background));
}
tv=(TextView) convertView.findViewById(android.R.id.text1);
tv.setText(inventatioItems[position]);
if(listInventario.isItemChecked(position)){
//background Color of selected items
convertView.setBackgroundColor(Color.BLUE);
}
else{
convertView.setBackgroundColor(Color.WHITE);
}
return convertView;
}
}
}

ListView OnClickListener is not working within Fragment

I'm trying to put a listener to my listview, which is inside my fragment. I've tried a few ways to do it, but still not working. I cannot make the other view focusable="false" because there is an EditText above the listview. Everytime I click the item, it calls the getView in the JSONAdapter that I created. Here is my XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:focusable="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"/>
<EditText
android:id="#+id/searchquery"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="Search"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/list">
</ListView>
</LinearLayout>
Here is my Fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
mJSONAdapter = new JSONAdapter(getActivity(), inflater);
View v = inflater.inflate(R.layout.header, container, false);
return v;
}
#Override
public void onViewCreated(View view,Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView lv = (ListView) getView().findViewById(android.R.id.list);
// Set the ListView to use the ArrayAdapter
lv.setAdapter(mJSONAdapter);//isi datany pk json adapter
lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),Integer.toString(position),Toast.LENGTH_SHORT).show();
JSONObject jsonObject = (JSONObject) mJSONAdapter.getItem(position);//ambil item yg diclick
String raceid = jsonObject.optString("id","");//ambil cover id yg diklik, argumen kedua itu klo null defaultny apa
// create an Intent to take you over to a new DetailActivity
Intent detailIntent = new Intent(getActivity(), DetailActivity.class);
// pack away the data about the cover
// into your Intent before you head out
detailIntent.putExtra("raceid", raceid);
// start the next Activity using your prepared Intent
startActivity(detailIntent);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
new RetrieveFeedTask().execute();
}
You can try this code.
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
// do your work
}
});
It appears that I choose the wrong method. It should be OnItemClickListener(), instead I choose OnItemSelectedListener()

Button onclick inside fragment is not working

I am trying to set / override the onclick method for a button (R.id.buy_button) inside one of my views (inside a fragment). The application doesn't return errors. However it does not trigger the onclick method. I'm not sure if my implementation is wrong or perhaps my button is incorrectly configured. Any help / comments / guidance would be appreciated.
My onCreateView is here:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_item, container, false);
Button b = (Button) view.findViewById(R.id.buy_button);
b.setOnClickListener(this);
return inflater.inflate(R.layout.fragment_item_list, container, false);
}
My entire fragment code:
public static class AlbumsFragment extends ListFragment implements View.OnClickListener {
private static final String ARG_SECTION_NUMBER = "section_number";
public AlbumsFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle b){
super.onActivityCreated(b);
ListView listView = getListView();
List<Album> albums = null;
albums = Album.listAll(Album.class);
Log.i("ALBUMS", albums.toString());
ArrayAdapter<Album> adapter =
new ArrayAdapter<Album>(getActivity(), R.layout.list_item, R.id.textView, albums);
if (!albums.equals("")) {
listView.setAdapter(adapter);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_item, container, false);
Button b = (Button) view.findViewById(R.id.buy_button);
b.setOnClickListener(this);
return inflater.inflate(R.layout.fragment_item_list, container, false);
}
public void gotoPurchaseWeb() {
Context context = getActivity().getApplicationContext();
Intent intent = new Intent(context, PurchaseSong.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
public static AlbumsFragment newInstance(int sectionNumber) {
AlbumsFragment fragment = new AlbumsFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buy_button:
Context context = getActivity().getApplicationContext();
Intent intent = new Intent(context, PurchaseSong.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
break;
}
}
}
My list_item.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" >
<!-- ListRow Left sied Thumbnail image -->
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:weightSum="1"
android:showDividers="middle|end"
android:visibility="visible">
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip"
android:src="#drawable/black"/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textView"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="wrap_content"
android:textSize="16sp"
android:layout_marginTop="#dimen/zero_space"
android:layout_marginBottom="#dimen/zero_space"
android:paddingTop="3dp"
android:paddingLeft="8dp"
android:paddingRight="5dp"
android:paddingBottom="0dp"
android:layout_weight="24.33" />
</LinearLayout>
<Button
style="#style/ButtonText"
android:layout_width="wrap_content"
android:layout_height="#dimen/button_height"
android:text="#string/buy_album"
android:id="#+id/buy_button"
android:background="#drawable/blue_button"
android:paddingTop="7dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="10dp" />
My entire project:
https://github.com/markbratanov/MyFitPlayer/tree/master/Player/src/main/java/com/markbratanov/myfitplayer
Any help would be appreciated. Thanks.
You should return your View instead of returning new inflated instance of your View in onCreateView callback function inside of your Fragment.
return inflater.inflate(R.layout.fragment_item_list, container, false);
instead use :
return view;
do this in onCreateView view method u need to inflate fragment like this for button click
View view = inflater.inflate(R.layout.fragment_blank3,
container, false);
Button bt1=(Button)view.findViewbyId(R.id.buttton);
bt1.setOnclick...
//then return in on create view.
return view;
I had the same problem. My button onclick listener was not working inside the fragment.
Try this: add the android:onclick="" inside the button XML before the closing TAG and create a class inside the mainActivity.java file having the same name as the class name you declared inside the XML. Then do whatever you want to do in the onclick event. Write it inside the class you created recently for the click event.

Can't set a Custom Listview on ListFragment

I'm trying to set a Custom Listview layout on a ListFragment, I've been reasearching everywhere and i still cant get it to work. I'm new programming with android, so I'll really appreciate your help.
This is my listFragment class
public class ListCins extends ListFragment {
public static ArrayList<Cin> cins;
private ListView listView;
private pListAdapter mAdapter;
public static ListCins newInstance() {
ListCins f = new ListCins();
return f;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Los fragments soportan presentar un msj cuando la lista esta vacia.
setEmptyText("Nothing yet, but working");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cins = new ArrayList<Cin>();
cins.add(new Cin("Agenter", 1));
cins.add(new Cin("Ora", 2));
cins.add(new Cin("Vistia", 2));
cins.add(new Cin("Bluel", 2));
mAdapter = new pListAdapter(this.getActivity(), cins);
setListAdapter(mAdapter);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setEmptyText("Nothing yet 2, but working");
registerForContextMenu(getListView());
setHasOptionsMenu(true);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Toast mTosat = Toast.makeText(this.getActivity(),"clicked:"+String.valueOf(position)+" "+cins.get(position).nombre , 200);
mTosat.show();
}
}
And this is the list_fragment.xml i want to apply to the listfragment.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
<TextView
android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No data" />
</LinearLayout>
I also have a custom arrayAdapter, but i dont know if it has something to do with the custom listview layout.
Thanks in advance...
You need to override onCreateView and inflate/return your custom layout. The ListFragment should handle the rest for you. This is described on the Screen Layout section of http://developer.android.com/reference/android/app/ListFragment.html
Thanks NasaGeek, I was trying to inflate it just like they said, like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.list_fragment, container, false);
return view;
}
but it wasen't working, then i found the problem. For some reason this method makes the code goes like crazy.
setEmptyText("Nothing yet, but working");
If you could explain me why, it will be awesome.
Thanks.

drag-sort-list-view item click does not work

I use DragSortListView library. It works fine - drag and remove items from my listview, but i also want to click ListView items. When I set OnClickListener it don't work. What could be the problem? Sorry for my bad english
My fragment:
private DragSortListView listView;
private MakeSingleBetAdapter adapter;
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
MyLog.d(TAG, "onCreateView");
BugSenseHandler.initAndStartSession(getActivity(), APP_Parameters.BugSense);
view = inflater.inflate(R.layout.fragment_make_single_bet,
container, false);
listView = (DragSortListView) view.findViewById(R.id.makeBetList);
listView.setRemoveListener(this);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(getActivity(), "Click: " + position, Toast.LENGTH_SHORT).show();
}
});
cursor = dbHelper.getAllBets();
adapter = new MakeSingleBetAdapter(getActivity(), cursor, 3, dbHelper);
listView.setAdapter(adapter);
return view;
}
#Override
public void remove(int which) {
Cursor cursorId = (Cursor) (listView.getItemAtPosition(which));
String id = cursorId.getString(cursor
.getColumnIndex(DBHelper.COL_BET_ID));
dbHelper.deleteBetById(id);
adapter.swapCursor(dbHelper.getAllBets());
}
My XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/ch.bettings"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="5dp"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:orientation="vertical" >
....
<com.mobeta.android.dslv.DragSortListView
android:id="#+id/makeBetList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/View1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:cacheColorHint="#color/slidingMenu"
android:divider="#b5b5b5"
app:drag_enabled="true"
app:drag_start_mode="onMove"
app:remove_enabled="true"
app:remove_mode="flingRemove"
app:sort_enabled="false" />
....
</RelativeLayout>
If I add ClickListener in my adapter - it work's fine, but I can not drag list items
Try adding these to your listview row:
android:focusable="false"
android:focusableInTouchMode="false"
This worked for me, I have been clicking the item in the list and its going to touch event so my code is as below. I wanted to only perform Onclick but not Ontouch just override the method and do nothing.
private DragSortListView list;
list = view.findViewById(android.R.id.list);
list.addHeaderView(footerView);
list.setFocusable(false);
list.setHeaderDividersEnabled(false);
list.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Toast.makeText(getActivity(),"its a touch" , Toast.LENGTH_LONG).show();
Log.d("stack", "TOUCH EVENT");
return false;
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),"Position :"+position+" ListItem : " +id , Toast.LENGTH_LONG).show();
Log.i("edit recipe click", "clicked");
EditableIngredient ingredient = (EditableIngredient) parent.getItemAtPosition(position);
host.handleIngredientSelected(ingredient);
}
});
return view;
}
My Xml looks like
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mobeta.android.dslv.DragSortListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
app:drag_handle_id="#id/drag_handle"
app:float_background_color="#android:color/white"
/>
</FrameLayout>

Categories

Resources