My Problem is the last item in the listview is not displaying even though it has been added to the adapter and as well as in the list as i can see the number of items in the adapter is ok. Is it the problem with the layout? this is my layout
<?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:background="#drawable/golive_bg"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/Room"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus android:layout_width="wrap_content" />
</EditText>
<Button
android:id="#+id/Search1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Search" />
<ImageButton
android:id="#+id/CreateRoomimageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/closed_doorplus" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/listRooms"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fastScrollEnabled="true"
android:transcriptMode="alwaysScroll">
</ListView>
</LinearLayout>
</LinearLayout>
This is my class activity
public class chatRoomsListActivity extends Activity implements OnScrollListener {
private static String Password;
private ListView lv;
private static Collection<HostedRoom> rooms;
private static ArrayList<String> Roomlist = new ArrayList<String>();
private static Handler mHandler = new Handler();
private Button SearchButton;
private ImageButton CreateButton;
private EditText EditTextSearch;
private String Search;
private String RoomName;
private static ChatRoomListAdapter adapter;
private static String Nickname="";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_rooms);
SearchButton=(Button)findViewById(R.id.Search1);
CreateButton=(ImageButton)findViewById(R.id.CreateRoomimageButton);
lv = (ListView) findViewById(R.id.listRooms);
adapter = new ChatRoomListAdapter(getApplicationContext(),
R.layout.chat_rooms_wrapper);
lv.setAdapter(adapter);
//ScrollView.measureChildWithMargins();
try {
populate_RoomList();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
addListenerOnButton();
/*
arrayAdapter = new ArrayAdapter<String>(
this,android.R.layout.simple_list_item_1,Roomlist);
lv.setAdapter(arrayAdapter);
*/
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parnet,
android.view.View view,
int position, long id) {
setRoomName(ChatRoomListAdapter.getItemName(position));
showOptionDialog();
}
});
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
CreateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
createRoomDialog();
}
});
SearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditTextSearch=(EditText) findViewById(R.id.Room);
Search=EditTextSearch.getText().toString();
//Search=Search.concat("*");
try {
// populate_RoomList();
getSearchlist();
// updateList();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void getSearchlist() throws XMPPException{
Roomlist.clear();
adapter.clear();
ChatRoomListAdapter.getChatRoom().clear();
rooms=getHostedRooms(MyService.getConnection(),"conference."+
MyService.getDomain());
System.out.println("in getsearch");
for (HostedRoom h : rooms)
{
System.out.println(h.getName().toString()+" contain " +Search);
if(h.getName().toString().contains(Search)){
System.out.println("roomlist= " +h.getJid().toString());
Roomlist.add(h.getName());
System.out.println("ChatRooms.IsRoomPassProtected(h.getName())==
"+ChatRooms.IsRoomPassProtected(h.getName()));
if(ChatRooms.IsRoomPassProtected(h.getName())==true){
adapter.add(new ChatRoom(h.getName(),true));
}
else if(ChatRooms.IsRoomPassProtected(h.getName())==false){
adapter.add(new ChatRoom(h.getName(),false));
}
}
}
System.out.println("Adapter count="+adapter.getCount());
}
private void populate_RoomList() throws XMPPException {
//chatRoomsList.getRooms();"
Roomlist.clear();
adapter.clear();
//rooms.clear();
ChatRoomListAdapter.getChatRoom().clear();
rooms=getHostedRooms(MyService.getConnection(),"conference."+
MyService.getDomain());
//System.out.println(rooms.iterator().next().getName());
for (HostedRoom h : rooms)
{
System.out.println("roomlist= " +h.getName().toString());
Roomlist.add(h.getName());
System.out.println("ChatRooms.IsRoomPassProtected(h.getName())==
"+ChatRooms.IsRoomPassProtected(h.getName()));
if(ChatRooms.IsRoomPassProtected(h.getName())==true){
adapter.add(new ChatRoom(h.getName(),true));
}
else if(ChatRooms.IsRoomPassProtected(h.getName())==false){
adapter.add(new ChatRoom(h.getName(),false));
}
}
System.out.println("Adapter count="+adapter.getCount());
}
public void setRoomName(String roomName) {
RoomName = roomName;
}
public static Collection<HostedRoom> getHostedRooms(Connection connection, String serviceName)
throws XMPPException {
List<HostedRoom> answer = new ArrayList<HostedRoom>();
ServiceDiscoveryManager discoManager = new
ServiceDiscoveryManager(connection);
DiscoverItems items = discoManager.discoverItems(serviceName);
for (Iterator<DiscoverItems.Item> it = items.getItems(); it.hasNext();) {
answer.add(new HostedRoom(it.next()));
}
return answer;
}
}
And this is my custom adapter
public class ChatRoomListAdapter extends ArrayAdapter<ChatRoom> {
private TextView name;
private static List<ChatRoom> ChatRoom = new ArrayList<ChatRoom>();
private LinearLayout wrapper;
private ImageView lock;
public ChatRoomListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public static List<ChatRoom> getChatRoom() {
return ChatRoom;
}
public static void setChatRoom(List<ChatRoom> chatRoom) {
ChatRoom = chatRoom;
}
public ChatRoom getItem(int index) {
return ChatRoomListAdapter.ChatRoom.get(index);
}
public static String getItemName(int index) {
return ChatRoomListAdapter.ChatRoom.get(index).name;
}
public static void setfriends(List<Friends> friends) {
FriendListAdapter.setFriends(friends);
}
public void add(ChatRoom object) {
System.out.println("IN Chat room list adapter "+" addded");
ChatRoomListAdapter.ChatRoom.add(object);
super.add(object);
}
public void remove(ChatRoom object) {
ChatRoom.remove(object);
super.remove(object);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater)
this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.chat_rooms_wrapper, parent, false);
}
wrapper = (LinearLayout) row.findViewById(R.id.C_R_wrapper);
name = (TextView) row.findViewById(R.id.C_R_RoomName);
lock=(ImageView)row.findViewById(R.id.C_R_Lock);
try {
Log.d("Chat room adapter", "heere");
ChatRoom CR= getItem(position);
System.out.println("name= "+CR.name);
name.setText(CR.name);
if(CR.lock==true)
{
lock.setImageResource(R.drawable.lock_lock_icon);
}else{
lock.setImageResource(R.drawable.lock_unlock_icon);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return row;
}
public Bitmap decodeToBitmap(byte[] decodedByte) {
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
}
Thanks in advance.
Add this line to your Viewpager
android:layout_marginBottom="?attr/actionBarSize"
because the size you don't have at the bottom is exactly the size taken by your Toolbar
Example with RecyclerView
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_trips"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:layout_marginBottom="?attr/actionBarSize"/>
Example with Viewpager
<android.support.v4.view.ViewPager
android:id="#+id/viewpager_trip_history"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize" />
Try this you can solve your problem with this:
You just need to change your xml file as below:
<?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:background="#drawable/golive_bg"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="6" >
<EditText
android:id="#+id/Room"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:layout_weight="4">
<requestFocus android:layout_width="wrap_content" />
</EditText>
<Button
android:id="#+id/Search1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Search"
android:layout_weight="1" />
<ImageButton
android:id="#+id/CreateRoomimageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/closed_doorplus"
android:layout_weight="1" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listRooms"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fastScrollEnabled="true"
android:transcriptMode="alwaysScroll">
</ListView>
</RelativeLayout>
</LinearLayout>
You can get the last item inside getView of the Adapter and change it layout params height by setLayoutParams. But the minus is you have to correct other items height because the height will change when scroll the list up/down
Maybe its very simple. Try to set the layout_height of your listview in the xml file to wrap_content.
android:layout_height="wrap_content"
Try to set the second LinearLayout holding the Listview to match_parent height... It seems like your LinearLayout is growing with the ListView (wrap_content) out of your screen space
Related
I have next problem with a list view: So on the layout (prod_row) I set an image view(rvCls) that I want to delete an item while clicked. It deletes an item, but is always the last one. If I close this activity and I reopen it, it deletes the correct item, but what should I do to see the change instantly and not have to refresh the page?
on the Cos class I build logic for list view and cosAdapter is the Adapter class for my list view
COS class the one with the list view
public class Cos extends AppCompatActivity {
ListView lvProd;
SwipeMenuListView listView;
Button btnTrm, btnCls;
TextView tvTotal;
DatabaseReference mDatabase;
ArrayList<Produs> list = new ArrayList<Produs>();
String email;
Integer contor = 1;
ImageView rvCls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cos);
FirebaseAuth mAuth;
mAuth=FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
email = currentUser.getEmail();
tvTotal = findViewById(R.id.tvTotal);
btnTrm = findViewById(R.id.btnTrm);
Intent i = getIntent();
list = (ArrayList<Produs>) i.getSerializableExtra("set");
Double total = 0.0;
for(Produs p: list){
total+= Double.valueOf(p.getPret()) * p.getQt();
}
Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY);
if(hour == 15){
total /= 2;
}
tvTotal.setText("Total: " + String.valueOf(total) + " lei");
btnTrm = findViewById(R.id.btnTrm);
btnCls = findViewById(R.id.btnCls);
// lvProd = findViewById(R.id.lvProd);
listView = (SwipeMenuListView) findViewById(R.id.listView);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Istoric");
try {
ArrayAdapter<Produs> adapter = new cosAdapter(this, 0 ,list);
listView.setAdapter(adapter);
}catch (Exception e){
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
btnCls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtra("set",(Serializable)list);
startActivity(intent);
}catch (Exception e){
Toast.makeText(Cos.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
btnTrm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(Produs p : list){
IstoricData id= new IstoricData(email,p.getNume(),false,p.getQt());
Task t = mDatabase.push().setValue(id);
contor ++;
t.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
Toast.makeText(Cos.this, "Comanda a fost trimisa cu succes", Toast.LENGTH_SHORT).show();
}
});
t.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Cos.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
}
}
COS adapter the adapter class for my list view adapter
public class cosAdapter extends ArrayAdapter<Produs> {
private Context context;
//private List<Produs> produse;
ArrayList<Produs> produse;
public cosAdapter(Context context, int resource, ArrayList<Produs> objects){
super(context, resource, objects);
this.context = context;
this.produse = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
RecyclerView.ViewHolder holder;LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
TextView rvNume, rvPret, rvCantitate, rvQT;
ImageView rvImage;
CardView cardView;
ImageView rvCls;
Produs model = produse.get(position);
View view = inflater.inflate(R.layout.prod_row, null);
View cos = inflater.inflate(R.layout.activity_cos, null);
rvNume = view.findViewById(R.id.rvNume);
rvCantitate = view.findViewById(R.id.rvCantitate);
rvPret = view.findViewById(R.id.rvPret);
rvImage = view.findViewById(R.id.rvImage);
cardView = view.findViewById(R.id.cv);
rvQT = view.findViewById(R.id.rvQT);
rvCls = view.findViewById(R.id.rvCls);
rvPret.setText("Pret: "+model.getPret()+ " lei");
rvNume.setText(model.getNume());
rvCantitate.setText("Cantitate: "+model.getCantitate()+" grame");
rvQT.setText("Numar: x" +String.valueOf(model.getQt()));
Picasso.get().load(model.getImage()).into(rvImage);
rvCls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
produse.remove(position);
cosAdapter.super.notifyDataSetChanged();
}
});
return view;
}
}
My layout for each item in list view
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true">
<ImageView
android:id="#+id/rvCls"
android:layout_width="34dp"
android:layout_height="34dp"
android:layout_alignParentRight="true"
android:layout_gravity="right"
android:layout_margin="5dp"
android:layout_toRightOf="#+id/view"
android:clickable="true"
android:gravity="right"
app:srcCompat="#drawable/ic_baseline_close_24" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/rvImage"
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_weight="2"
android:maxHeight="50dp"
tools:srcCompat="#tools:sample/avatars" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/rvNume"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textStyle="bold" />
<TextView
android:id="#+id/rvCantitate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/rvPret"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/rvQT"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
There are 2 ways you could fix your code:
1.) Set position value as tag to your rvCls and fetch this tag for usage of position in your ClickListener
rvCls.setTag(position);
rvCls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
produse.remove((int)v.getTag());
notifyDataSetChanged();
}
});
2.) Use a variable finalPosition in getView and use that as position inside ClickListener.
final int finalPosition = position;
rvCls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
produse.remove(finalPosition);
notifyDataSetChanged();
}
});
I'm facing problem with list view, there is a custom card layout view which should appear in the list view. This is main FirstActivity.java file including the adapter class, followed by the activity_first.xml, card_layout.xml, and a screenshot. My problem is that when I run this app, it installs successfully but the list view is not visible at all:
public class FirstActivity extends AppCompatActivity {
private Toolbar toolbar;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
setupUIViews();
toolbarSettings();
setupListView();
}
catch (java.lang.NullPointerException exception) {
exception.printStackTrace();
}
}
private void setupUIViews () {
try {
toolbar = (Toolbar) findViewById(R.id.ToolbarMain);
listView = (ListView) findViewById(R.id.lv_main);
}
catch (java.lang.NullPointerException exception) {
exception.printStackTrace();
}
}
private void toolbarSettings() {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("TimeTable");
}
private void setupListView () {
try {
String[] title = getResources().getStringArray(R.array.Main);
String[] description = getResources().getStringArray(R.array.Desc);
adapter adapter = new adapter(this, title, description);
listView.setAdapter(adapter);
} catch (java.lang.NullPointerException exception) {
exception.printStackTrace();
}
}
public class adapter extends BaseAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
private TextView title, description;
private String[] titleArray;
private String[] descriptionArray;
private ImageView imageView;
public adapter(Context context, String[] titleArray, String[] descriptionArray) {
mContext = context;
titleArray = titleArray;
descriptionArray = descriptionArray;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
int length = 0;
try {
length = titleArray.length;
}
catch (java.lang.NullPointerException exception) {
exception.printStackTrace();
}
return length;
}
#Override
public Object getItem(int position) {
return titleArray[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null ) {
convertView = layoutInflater.inflate(R.layout.card_layout, null);
}
title = (TextView)convertView.findViewById(R.id.tv_heading);
description = (TextView)convertView.findViewById(R.id.tv_desc);
imageView = (ImageView)convertView.findViewById(R.id.iv_main);
title.setText(titleArray[position]);
description.setText(descriptionArray[position]);
if (titleArray[position].equalsIgnoreCase("TimeTable")) {
imageView.setImageResource(R.drawable.timetable);
}
else if (titleArray[position].equalsIgnoreCase("Subjects")) {
imageView.setImageResource(R.drawable.calender);
}
else if (titleArray[position].equalsIgnoreCase("Faculty")) {
imageView.setImageResource(R.drawable.contact);
}
else
imageView.setImageResource(R.drawable.settings);
return convertView;
}
}
}
Here is the first_activity.xml:
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".FirstActivity">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="#color/colorPrimary"
android:id="#+id/ToolbarMain">
</android.support.v7.widget.Toolbar>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_below="#+id/ToolbarMain"
android:divider="#null"
android:id="#+id/lv_main">
</ListView>
</RelativeLayout>
Here is the card_layout.xml file:-
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:elevation="4dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="85dp"
android:layout_height="105dp"
android:layout_marginStart="10dp"
android:id="#+id/iv_main"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/iv_main"
android:textStyle="bold"
android:layout_marginBottom="5dp"
android:text="IshaanNagwani"
android:textSize="20sp"
android:id="#+id/tv_heading"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IshaanNagwani"
android:textSize="16sp"
android:layout_below="#id/tv_heading"
android:layout_toEndOf="#id/iv_main"
android:id="#+id/tv_desc"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_desc"
android:layout_alignBottom="#id/iv_main"
android:layout_alignParentRight="true"
android:layout_marginTop="29sp"
android:text="IshaanNagwani"
android:textAlignment="center"
android:textSize="12sp"
android:id="#+id/tv_third"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
And finally, this is my strings.xml:-
<resources>
<string name="app_name">TimeTable</string>
<string-array name="Main">
<item>TimeTable</item>
<item>Subjects</item>
<item>Faculty</item>
<item>Resources</item>
</string-array>
<string-array name="Desc">
<item>desc_1</item>
<item>desc_2</item>
<item>desc_3</item>
<item>desc_4</item>
</string-array>
</resources>
I am new in android and this is my first post. I'm working with ListView. Apparently I am doing something quite wrong, but I cant figure out what is it.
This is the screenshot of the app, after it is gets completely installed:
In adapter constructor, some class variables's names are same with parameters's name. So, all manipulation will just be done for parameters, it makes size of this.titleArray will be zero then getCount() method always return 0 then no item appear on your activity. So you must use this to reference to the class variables. Modify your code as following:
public adapter(Context context, String[] titleArray, String[] descriptionArray) {
mContext = context;
this.titleArray = titleArray;
this.descriptionArray = descriptionArray;
layoutInflater = LayoutInflater.from(context);
}
I am a beginner in android.I have a ListView containing a spinner,edittext and an imagebutton which is for deleting that row.The spinner is populated from a list.There is a add button which add these item to the listview when each time it clicks.If i select an item in a spinner then i need to remove that item from all the other spinner in that listview and also the items become visible when i deleted the selected spinner row or change the selected item in the spinner.Say for simplicity that my Spinners are populated with the following data:
{"data1", "data2", "data3", "data4", "data5"};
For example, if I select my first ListView's Spinner value to be "data3" and then the "data3" entry disappears from all the other ListView Spinner and this will appears back only when i change the selected value in the first listview spinner or deleting that row, similarly for each ListView spinner.How to do this? Somebody please help me.Below is my code.
receipt_trans.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="vertical" >
<LinearLayout
android:id="#+id/LinLay3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/txtGrossAmt"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:text="Gross amount :"
android:textColor="#000" />
<EditText
android:id="#+id/edtGrossAmt"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:background="#drawable/border"
android:focusableInTouchMode="false"
android:layout_toRightOf="#+id/txtAccount" />
<Button
android:id="#+id/btnAddRow"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:layout_marginLeft="10dp"
android:text="Add Row"
android:layout_toRightOf="#+id/edtGrossAmt" />
</LinearLayout>
<LinearLayout
android:id="#+id/LinLay4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/txtFundStores"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:text="Fund Stores"
android:textColor="#000" />
</LinearLayout>
<ListView
android:id="#+id/lstFundStore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" >
</ListView>
</LinearLayout>
fundstore_row.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:orientation="horizontal" >
<Spinner
android:id="#+id/spnAccount"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignBottom="#+id/imageButton1"
android:layout_marginBottom="15dp"
android:layout_toRightOf="#+id/textView1" />
<EditText
android:id="#+id/edtAccAmount"
android:layout_width="0sp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:inputType="numberDecimal"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<ImageButton
android:id="#+id/imgDel"
android:layout_width="20sp"
android:layout_height="fill_parent"
android:contentDescription="delete"
android:src="#drawable/delete2" />
</LinearLayout>
ReceiptTransaction.java:
public class ReceiptTransaction extends Activity{
RestTemplate restTemplate=new RestTemplate();
String constr="http://192.168.1.14:8080/ServPro/stock/";
ListView lstFund;
Button btnAddRw;
private FundStoreAdapter adapter;
ArrayList<COAAccount> subList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.receipt_trans);
lstFund=(ListView) findViewById(R.id.lstFundStore);
btnAddRw=(Button) findViewById(R.id.btnAddRow);
setFundStore();
setDeduction();
btnAddRw.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
adapter.add(new FundReceipt(subList.get(0), 0.0f));
}
});
}
public void setFundStore(){
String accList=restTemplate.getForObject(constr+"getAllCBOnly", String.class);
Gson gson = new Gson(); // Or use new GsonBuilder().create();
CoaAccountList dropCoaList = gson.fromJson(accList, CoaAccountList.class);
subList=new ArrayList<COAAccount>();
COAAccount newAccount = new COAAccount();
newAccount.setFunds(-1, -2, "Select...", "select", "SE",0.0f);
subList.add(newAccount);
ArrayList<COAAccount> listItem=(ArrayList<COAAccount>) dropCoaList.getCoaList();
for(COAAccount addCoa:listItem){
subList.add(addCoa);
}
adapter=new FundStoreAdapter(ReceiptTransaction.this, R.layout.fundstore_row, new ArrayList<FundReceipt>(),subList);
lstFund.setAdapter(adapter);
adapter.add(new FundReceipt(subList.get(0), 0.0f));
}
public void setDeduction(){
}
}
FundStoreAdapter.java:
public class FundStoreAdapter extends ArrayAdapter<FundReceipt> {
protected static final String LOG_TAG = FundStoreAdapter.class.getSimpleName();
private final Context context;
private final int resourceID;
private List<FundReceipt> items;
private ArrayList<COAAccount> list;
public FundStoreAdapter(Context context, int resource, List<FundReceipt> items, ArrayList<COAAccount> subList) {
super(context, resource,items);
this.context = context;
this.resourceID = resource;
this.items=items;
this.list=subList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
FundStoreHolder holder = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View rowView = inflater.inflate(resourceID, parent, false);
holder=new FundStoreHolder();
holder.fundRecpt=items.get(position);
holder.imgDeleteFund=(ImageButton) rowView.findViewById(R.id.imgDel);
holder.imgDeleteFund.setTag(holder.fundRecpt);
removeRow(holder);
holder.edtAmount=(EditText) rowView.findViewById(R.id.edtAccAmount);
setValueTextListeners(holder);
holder.spnAcct=(Spinner) rowView.findViewById(R.id.spnAccount);
setNameTextChangeListener(holder);
rowView.setTag(holder);
setupItem(holder);
return rowView;
}
private void removeRow(FundStoreHolder holder) {
holder.imgDeleteFund.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FundReceipt itemToRemove = (FundReceipt)v.getTag();
remove(itemToRemove);
}
});
}
private void setupItem(FundStoreHolder holder) {
holder.edtAmount.setText(String.valueOf(holder.fundRecpt.getAmount()));
//ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list);
ArrayAdapter<COAAccount> dataAdapter =new ArrayAdapter<COAAccount>(context, android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spnAcct.setAdapter(dataAdapter);
holder.spnAcct.setSelection(dataAdapter.getPosition(holder.fundRecpt.getSelAcct()));
}
public static class FundStoreHolder{
FundReceipt fundRecpt;
Spinner spnAcct;
EditText edtAmount;
ImageButton imgDeleteFund;
}
private void setNameTextChangeListener(final FundStoreHolder holder) {
holder.spnAcct.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
holder.fundRecpt.setSelAcct((COAAccount) parent.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
private void setValueTextListeners(final FundStoreHolder holder) {
holder.edtAmount.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try{
holder.fundRecpt.setAmount(Float.parseFloat(s.toString()));
}catch (NumberFormatException e) {
Log.e(LOG_TAG, "error reading float value: " + s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
}
FundReceipt.java:
public class FundReceipt implements Serializable {
private static final long serialVersionUID = -5435670920302756945L;
private Float amount = 0.0f;
private COAAccount selAcct;
public FundReceipt(COAAccount selAcct, Float amount) {
this.setAmount(amount);
this.setSelAcct(selAcct);
}
public Float getAmount() {
return amount;
}
public void setAmount(Float amount) {
this.amount = amount;
}
public COAAccount getSelAcct() {
return selAcct;
}
public void setSelAcct(COAAccount selAcct) {
this.selAcct = selAcct;
}
}
I faced same problem but i could succeed to remove selected item from list After that i did an alter net. Selected item shown highlighted state in drop down list. I know my answer was not fulfill your question but want to share with you.
Your spinner:
<Spinner
android:id="#+id/sp_handi_cap"
style="#style/SpinnerAppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="#drawable/selector_rectangular_gray_trans_bg"
android:descendantFocusability="afterDescendants"
android:gravity="start"
android:minWidth="250dp"
android:padding="5dp"
android:singleLine="true" />
selector_rectangular_gray_trans_bg.xml
<solid android:color="#android:color/transparent" />
<stroke
android:width="1dp"
android:color="#color/gray6" />
<corners
android:bottomLeftRadius="0dp"
android:bottomRightRadius="0dp"
android:topLeftRadius="0dp"
android:topRightRadius="0dp" /></shape>
Create layout :
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/selector_spinner_item_activited"
android:gravity="center"
android:padding="3dp"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textSize="12sp" />
selector selector_spinner_item_activited.xml :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/selector_rectangular_black_trans_bg" android:state_activated="true"/>
<item android:drawable="#android:color/transparent"/>
</selector>
Create adapter :
ArrayAdapter objAdapter = new ArrayAdapter<String>(AddStudentActivity.this,
R.layout.layout_text_single_line_activated, getResources()
.getStringArray(R.array.arr_handicap_option));
set adapter in spinner object.
spinner.setAdapter(objAdapter);
I'm trying to implement Custom ListView (i.e. ListView with custom Adapter) with Search Box, for that I have written the following XML code--
<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="match_parent"
android:orientation="vertical"
tools:context=".CustomListViewAndroidExample" >
<EditText
android:id="#+id/txtInputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search item.."
android:inputType="textVisiblePassword" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="20dp"
android:layout_weight="1" />
</LinearLayout>
My MenuListActivity code is---
public class MenuListActivity extends Activity
{
ListView list;
TextView txtInputSearch;
MenuListAdapter adapter;
public MenuListActivity CustomListView = null;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_list);
CustomListView = this;
setListData();
Resources res =getResources();
txtInputSearch=(TextView)findViewById(R.id.txtInputSearch);
list= ( ListView )findViewById( R.id.list ); // List defined in XML ( See Below )
adapter=new MenuListAdapter( CustomListView, CustomListViewValuesArr,res );
list.setAdapter( adapter );
txtInputSearch.addTextChangedListener(new TextWatcher()
{
#Override
public void afterTextChanged(Editable arg0)
{
// TODO Auto-generated method stub
String text = txtInputSearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3)
{
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
{
// TODO Auto-generated method stub
}
});
}
public void setListData()
{
for (int i = 0; i < 11; i++)
{
final ListModel objListModel = new ListModel();
objListModel.setMenu("Company "+i);
objListModel.setPrice("com.androidexample.customlistview:drawable/rihanna");
// sched.setUrl("http:\\www."+i+".com");
CustomListViewValuesArr.add(objListModel);
}
}
public void onItemClick(int mPosition)
{
ListModel tempValues = ( ListModel ) CustomListViewValuesArr.get(mPosition);
// SHOW ALERT
Toast.makeText(CustomListView,"Clicked",Toast.LENGTH_LONG).show();
}
}
See my Adapter class Below--
public class MenuListAdapter extends BaseAdapter implements OnClickListener
{
private Activity activity;
private ArrayList data;
private ArrayList<ListModel> arrayList;
private static LayoutInflater inflater=null;
public Resources res;
ListModel tempValues=null;
int i=0;
public MenuListAdapter(Activity paramActivity, ArrayList paramDataList, Resources paramResource)
{
activity = paramActivity;
data=paramDataList;
res = paramResource;
arrayList=new ArrayList<ListModel>();
arrayList.addAll(data);
inflater = ( LayoutInflater )activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount()
{
if(data.size()<=0)
return 1;
return data.size();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public static class ViewHolder
{
public TextView item_name;
public TextView item_price;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
ViewHolder holder;
if(convertView==null)
{
vi = inflater.inflate(R.layout.menu_list_row, null);
holder = new ViewHolder();
holder.item_name = (TextView) vi.findViewById(R.id.item_name);
holder.item_price=(TextView)vi.findViewById(R.id.item_price);
// holder.image=(ImageView)vi.findViewById(R.id.list_image);
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
if(data.size()<=0)
{
holder.item_name.setText("No Data");
}
else
{
tempValues=null;
tempValues = ( ListModel ) data.get( position );
holder.item_name.setText( tempValues.getMenu() );
holder.item_price.setText( tempValues.getPrice());
/* holder.image.setImageResource(
res.getIdentifier(
"com.androidexample.customlistview:drawable/"+tempValues.getImage()
,null,null));*/
vi.setOnClickListener(new OnItemClickListener( position ));
}
return vi;
}
public void onClick(View v)
{
Log.v("CustomAdapter", "=====Row button clicked=====");
}
private class OnItemClickListener implements OnClickListener
{
private int mPosition;
OnItemClickListener(int position)
{
mPosition = position;
}
public void onClick(View arg0)
{
MenuListActivity sct = (MenuListActivity)activity;
sct.onItemClick(mPosition);
}
}
// Filter Class
public void filter(String charText)
{
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0)
{
data.addAll(arrayList);
}
else
{
for (ListModel lm : arrayList)
{
if (lm.getMenu().toLowerCase(Locale.getDefault()).contains(charText))
{
data.add(lm);
}
}
}
notifyDataSetChanged();
}
}
In design mode, when I clicks on Graphical Layout It is showing me proper/expected view (i.e. Search box to the Top and ListView Below to the search Box) but when I run my application then it is showing only ListView and SearchBox (EditText) is invisible. Please Help.
Change listview layout height to android:layout_height="0dp" instead of android:layout_height="fill_parent"
<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="match_parent"
android:orientation="vertical"
tools:context=".CustomListViewAndroidExample" >
<EditText
android:id="#+id/txtInputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search item.."
android:inputType="textVisiblePassword" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginTop="20dp"
android:layout_weight="1" />
</LinearLayout>
Edit Use RelativeLayout instead of LinearLayout as
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<EditText
android:id="#+id/txtInputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:completionThreshold="1"
android:singleLine="true"/>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:layout_weight="1"
android:layout_below="#+id/txtInputSearch"
android:drawSelectorOnTop="false"/>
</RelativeLayout>
Edit
Use EditText in your code instead of TextView ,So change
TextView txtInputSearch;
to
EditText txtInputSearch;
And
txtInputSearch=(TextView)findViewById(R.id.txtInputSearch);
to
txtInputSearch=(EditText )findViewById(R.id.txtInputSearch);
The problem is that you are adding a weight into you ListView which would take all the space of your layout, instead dont put any weight on it just simply wrap its height and remove the android:layout_weight="1"
sample:
<?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="match_parent"
android:orientation="vertical"
tools:context=".CustomListViewAndroidExample" >
<EditText
android:id="#+id/txtInputSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search item.."
android:inputType="textVisiblePassword" />
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" />
</LinearLayout>
problem:
txtInputSearch=(TextView)findViewById(R.id.txtInputSearch);
You are casting it to a TextView not an EditText.
change it to this:
EditText txtInputSearch;
txtInputSearch=(EditText)findViewById(R.id.txtInputSearch);
I have prepared custom Listview in that i want to select one item from view so for that i have used RadioButton view for single choice item,but i customized it.Following is my total code ,because there may be error in the layout so please help me in solving this.
Activity:-
public class MainActivity extends Activity {
TextView tvEmpty;
ListView listView;
Spinner spnStage;
Button btnGet;
String sfrom;
ArrayList<String> arrayList;
StartFromAdapter arrayAdapter;
String[] stages = { "School", "Collage", "Office" };
String resultdata = "{\"Age\":{\"School\":[{\"Stage\":\"class1\",\"Name\":\"Classname1\"},{\"Stage\":\"class2\",\"Name\":\"ClassName2\"}],\"Collage\":[],\"Office\":[{\"Stage\":\"Office1\",\"Name\":\"Officename1\"},{\"Stage\":\"Office2\",\"Name\":\"Officename2\"}]}}";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvEmpty = (TextView) findViewById(R.id.emptytv);
listView = (ListView) findViewById(R.id.lstDemo);
spnStage = (Spinner) findViewById(R.id.spinner1);
btnGet = (Button) findViewById(R.id.button1);
ArrayAdapter<String> stageAdapter = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_spinner_item, stages);
stageAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnStage.setAdapter(stageAdapter);
arrayList = new ArrayList<String>();
spnStage.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long id) {
if (arrayList.size() > 0 && arrayList != null) {
arrayList.clear();
}
loadListView(parent.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnGet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = (Integer) v.getTag();
Log.i("SELECTED IN GET", "" + selectedPosition);
}
});
}
public void loadListView(String selectedItem) {
try {
JSONObject jObject = new JSONObject(resultdata);
JSONObject jAge = jObject.getJSONObject("Age");
JSONArray jSelectedItem = jAge.getJSONArray(selectedItem);
if (jSelectedItem.length() != 0) {
for (int i = 0; i < jSelectedItem.length(); i++) {
JSONObject jObj = jSelectedItem.getJSONObject(i);
arrayList.add(jObj.getString("Name"));
}
}
arrayAdapter = new StartFromAdapter(this, arrayList);
arrayAdapter.notifyDataSetChanged();
listView.setAdapter(arrayAdapter);
listView.setEmptyView(tvEmpty);
Log.i("BEFORE LISTVIEW ONCLICK", "THIS IS ADDRESSLIST");
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long id) {
sfrom = ((RadioButton) v.findViewById(R.id.startfromrb))
.getText().toString();
Log.i("STARTFROM", sfrom);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Adapter:-
public class StartFromAdapter extends BaseAdapter {
ArrayList<String> detailsArrayList;
Context context;
int selectedPosition = 0;
public StartFromAdapter(Context context, ArrayList<String> detailsArrayList) {
this.detailsArrayList = detailsArrayList;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return detailsArrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return detailsArrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout rowLayout = null;
if (convertView == null) {
rowLayout = (LinearLayout) LayoutInflater.from(context).inflate(
R.layout.listitem_view, parent, false);
} else {
rowLayout = (LinearLayout) convertView;
}
RadioButton rbStartFrom = (RadioButton) rowLayout
.findViewById(R.id.startfromrb);
rbStartFrom.setChecked(position == selectedPosition);
rbStartFrom.setTag(position);
rbStartFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
notifyDataSetInvalidated();
Log.i("IN ADAPTER", "" + selectedPosition);
}
});
rbStartFrom.setText(detailsArrayList.get(position));
return rowLayout;
}
}
MAINLAYOUT:-
<?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="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_marginBottom="60dp" >
</ListView>
<TextView
android:id="#+id/emptytv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_marginBottom="60dp"
android:gravity="center_vertical|center_horizontal"
android:text="No Records Found."
android:textSize="25sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="31dp"
android:text="Button" />
</RelativeLayout>
listitem_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"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/startfromrb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:focusable="false"
android:focusableInTouchMode="false"
android:lines="3"
android:paddingLeft="20dp"
android:text="RadioButton" />
</LinearLayout>
Update use code as per below
// On item click listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,long itemId) {
RadioButton btn=(RadioButton) view.findViewById(R.id.startfromrb);
String sfrom = btn.getText().toString();
arrayAdapter.setSelected((int)itemId);
Log.i("STARTFROM", sfrom);
}
});
//Add below function in adapter class
public void setSelected(int selectedPosition){
this.selectedPosition=selectedPosition;
notifyDataSetChanged();
}
Also remove from adapter
rbStartFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
notifyDataSetInvalidated();
Log.i("IN ADAPTER", "" + selectedPosition);
}
});
And add android:clickable="false" and set selectedPosition to -1 by default
The first I see is, that You have to change the reference to the Views where You want to set the other views below :
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1" <!-- correct: #id/spinner1 -->
android:layout_marginBottom="60dp" >
</ListView>
<TextView
android:id="#+id/emptytv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1" <!-- correct: #id/spinner1 -->
android:layout_marginBottom="60dp"
android:gravity="center_vertical|center_horizontal"
android:text="No Records Found."
android:textSize="25sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="31dp"
android:text="Button" />
</RelativeLayout>
But anyway, Your TextView is sitten directly above the listView, is this Your intention? If not, You have to set
android:layout_below="#+id/lstDemo"
Also, if You get any errors, please post the logcat output. If You just have problems with Your layout, please explain clear enough what exactly You want.
EDIT
try to get the selected item String like this:
final String item = (String) parent.getItemAtPosition(position);
loadListView(item);