ListView not showing items - android

I am trying to display a basic array of titles in a list view using fragments. And just not able to get the List items to show up. Wondering if anyone can shed some light. Also are there any good resources that help you understand Layouts well?
Here is my list_fragment.xml and the listfragment source file
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#id/android:list"
android:drawSelectorOnTop="false"
android:layout_weight="1"
android:layout_height="0dp"
android:layout_width="fill_parent">
</ListView>
</LinearLayout>
public class PublicTradeListFragment extends ListFragment
{
private String trades[];
public PublicTradeListFragment()
{
trades = new String [] {
"Trade ?",
"Give up ?",
"Trade again?"
};
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
ListAdapter listAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,trades);
setListAdapter(listAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.list_fragment,container,false);
}
#Override
public void onListItemClick(ListView list, View v, int position, long id) {
Toast.makeText(getActivity(), getListView().getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
}

You can try this in "on Create View" then
"return super.onCreateView(inflater, container, savedInstanceState);"
Check this link: http://wptrafficanalyzer.in/blog/a-listfragment-application-in-android/

Related

What should i use to create custom ListView in Fragment to suit my need?

I've been creating News application. I used this tutorial to create good-looking Navigation Drawer. It uses fragments for every category in Navigation List. I will be using provided API to get news (in the JSON format), and i need customized List View to show the list of news. When you click list item, it will open new view to show details of news. I've found several tutorials, but none of them worked for fragment. Please, tell me way to do it.
I'm new to Android Programming. This is my first project, though it is too hard for being first project. But i have to do it. Please, help!
Thanks beforehand!
Assuming you know how to create an adapter and a custom row layout from a tutorial that works for activities. Minor modifications will help you using fragments.
Your fragment should look like this:
public class NewFragment extends Fragment{
CustomAdapter listAdapter;
ListView listView;
ArrayList<Data> yourData; // Should be filled with data from your JSONParser;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
/*
* Use your custom adapter. in this example the adapter need
* the context and an array that contains your data
*/
listAdapter = new CustomAdapter(getActivity(),yourData);
...
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_fragment, container, false);
listView = (LsitView)view.findViewById(R.id.your_list);
listView.setAdapter(listAdapter);
...
}
}
You can use for this ListFragment:
Here is a fully customized example:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/frameLayout"/>
</RelativeLayout>
mylist.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">
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data"/>
</LinearLayout>
myitem.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">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text=""
android:id="#+id/txt_mytext" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment fr = mListFragment.newInstance();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().add(R.id.frameLayout, fr, "tag").commit();
}
}
mListFragment.java
public class mListFragment extends ListFragment {
public static mListFragment newInstance() {
mListFragment f = new mListFragment();
//Bundle args = new Bundle();
//f.setArguments(args);
return f;
}
public mListFragment() {}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String[] strings = {"a", "b", "c"};
ArrayAdapter<String> adapter = new LstAdapter(
getActivity(), R.layout.myitem,
strings);
setListAdapter(adapter);
return inflater.inflate(R.layout.mylist, null);
}
public class LstAdapter extends ArrayAdapter<String> {
private String[] mArray;
public LstAdapter(Context context, int textViewResourceId, String[] mList) {
super(context, textViewResourceId, mList);
mArray = mList;
}
#Override
public int getCount() {
return mArray.length;
}
#Override
public String getItem(int position) {
return mArray[position];
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.myitem, null);
}
TextView tvName = (TextView) v.findViewById(R.id.txt_mytext);
tvName.setText(mArray[position]);
return v;
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.d("123", position + "");
super.onListItemClick(l, v, position, id);
}
}

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()

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.

setOnItemClickListener not called in onCreatView method?

I am developing first android apps and I have a fragment class which extends SherlockListFragment. When I set setOnItemClickListener in onCreateView and implement onItemClick I'm getting no response when I click on a row(list). list display properly in my apps. I want when user click on row form listview my another activity will call. I goggled lot but not got proper answer.
I can't understand where is the problem. Can anyone tell me what am I doing wrong in following code?
following is the my code
public class ResidentialFragActivity extends SherlockListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle saved) {
View view = inflater.inflate(R.layout.project_list,container, false);
resListviewId = (ListView)view.findViewById(android.R.id.list);
linearProgress = (LinearLayout)view.findViewById(R.id.linlaHeaderProgress);
projectList = new ArrayList<HashMap<String,String>>();
new LoadProjects().execute();
resListviewId.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
Intent href = new Intent(getSherlockActivity(), ProjectDetailActivity.class);
// send project id to project detail activity to get list of Phases under that project
String proj_id = ((TextView) view.findViewById(R.id.projectId)).getText().toString();
href.putExtra("proj_id", proj_id);
getSherlockActivity().startActivity(href);
}
});
return view;
}
//inner class for network operation
private class LoadProjects extends AsyncTask<String, String, String> {
protected void onPreExecute() {
linearProgress.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
//call webservice
}
#Override
protected void onPostExecute(String result) {
linearProgress.setVisibility(View.GONE);
ListAdapter projAdapter = new SimpleAdapter(getSherlockActivity(),
projectList, R.layout.project_list_item,
new String[] {PROJ_ID,PROJ_NAME,EDIT_RIGHTS}, new int[]
{R.id.projectId,R.id.projectName,R.id.projectSubName});
//updating the UI
setListAdapter(projAdapter);
}
}
}
following is the layout for listview
<?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:layout_marginTop="10dp"
android:background="#color/White"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:divider="#drawable/divider"
android:focusableInTouchMode="true"
android:smoothScrollbar="true"
android:dividerHeight="1.5dp"
android:scrollbarThumbVertical="#drawable/divider"
android:drawSelectorOnTop="false"
android:listSelector="#drawable/list_selector">
</ListView>
</LinearLayout>
Thanks in advance..
You should override onListItemClick instead of instead of resListviewId.setOnItemClickListener .. as you are setting the adapter to the default one in setListAdapter(projAdapter);
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent href = new Intent(getSherlockActivity(), ProjectDetailActivity.class);
// send project id to project detail activity to get list of Phases under that project
String proj_id = ((TextView) view.findViewById(R.id.projectId)).getText().toString();
href.putExtra("proj_id", proj_id);
startActivity(href);
}

Categories

Resources