I wanted to show the part of next and previous items of the recyclerview as compared to the currently visible item (as in this third party library). However I managed to do so with my native recyclerview.
That's sound great to me, now I want to set the height of my currently visible item larger than the next and previous items to it as shown in the gif of the above mentioned library!
I have managed to show the next and previous items with my code as in the following stages:
1. Setting the recyclerview adapter as:
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
locationTypeFragmentBinding.mRecylerview.setLayoutManager(layoutManager);
locationTypeFragmentBinding.mRecylerview.setHasFixedSize(true);
final LocationTypePictureAdapter locationTypePictureAdapter =
new LocationTypePictureAdapter(getActivity(), locationDetails,false);
final SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(locationTypeFragmentBinding.mRecylerview);
locationTypeFragmentBinding.mRecylerview.post(new Runnable() {
#Override
public void run() {
locationTypeFragmentBinding.mRecylerview.
setAdapter(locationTypePictureAdapter);
}
});
2. My RecyclerView in the xml is:
<android.support.v7.widget.RecyclerView
android:id="#+id/mRecylerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/buttonsHolder"
android:clipToPadding="false"
android:orientation="horizontal"
android:padding="#dimen/_10sdp"
android:paddingStart="#dimen/_15sdp"
android:paddingEnd="#dimen/_15sdp"
android:scrollbarStyle="outsideOverlay"
android:visibility="gone"/>
3. My RecyclerView item xml is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainContainer"
android:layout_width="match_parent"
android:layout_height="#dimen/_200sdp">
<android.support.v7.widget.CardView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="#dimen/_5sdp"
android:layout_marginEnd="#dimen/_5sdp"
android:background="#android:color/transparent"
app:cardElevation="0dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/locationPicture"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
4. What I need to achieve is like:
I know I can use the above mentioned library, but I want to set the height of the currently visible item larger than the next and previous items of my recyclerview which are to be shown to the user.
Can somebody please figure out what I am doing wrong with my code?
Example Image of what I need
See Here
I am not familiar the library that you are using but You can also use CarouselLayoutManager to achieve this look, with this library you will have one elevated item that will be above all others and this will look bigger than the rest of the items.
How to use:
In your gradle:
implementation 'com.azoft.carousellayoutmanager:carousel:version'
When declaring an adapter:
final CarouselLayoutManager layoutManager = new CarouselLayoutManager(CarouselLayoutManager.VERTICAL);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
Edit:
If you want to do it natively you can do something like this:
Create recyclerView:
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fadingEdge="horizontal"
android:overScrollMode="never"
android:requiresFadingEdge="horizontal" />
Attach your recyclerView to SnapHelper like this:
LinearSnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
Now you need to provide the logic for your currently centered item:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
float position = (float) recyclerView.computeHorizontalScrollOffset() / (float) itemHeight;
int itemPosition = (int) Math.floor(position);
}
super.onScrollStateChanged(recyclerView, newState);
}
});
I had added animation to items of a recycleView using the below method. I hope it may solve your problem if you are able to do something similar to this
Try this changes in your onBindViewHolder of your recycleView adapter.
#Override
public void onBindViewHolder(#NonNull final CustomViewHolder holder, int position)
{
// do your work
setAnimation(holder.itemView, position);
}
and in setAnimation which receives the view and its position
void setAnimation(View view, int position) {
//this allows new views coming in the recycle view to slide to left while scrolling down and slide to right while scrolling up.
if (lastPosition < position) {
Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
view.startAnimation(animation);
} else {
Animation animation = AnimationUtils.loadAnimation(context, R.anim.slide_in_right);
view.startAnimation(animation);
}
lastPosition = position;
}
Similarly, if you know the position or location of view which is in middle, you can use your anim to zoom it up or zoom down other views in the recycleView.
If you cary about performance it is the best to do all animations things in Layout Manager. Tamir Abutbul gives you very good solution, why you want to reinvent the wheel? Without library there is ready layout manager you need : https://stackoverflow.com/a/41307581/2551094
So I'm working with my android app that takes data from firebase, basically a list of cars that I save into an ArrayList of a specific class. I want to show a list of CardView with one car object each, in other words, that each card displays the info about that car (model, km, price, etc). I know that the way I should do this is using a ListView in my layout, but I cant get the adapter to work.
The idea is that it shows something like this, but with car photos and stuff:
enter image description here
I'm not very familiarized with this type of structure since I started working on it recently, but I think I'm understand how it works. I made the cardview layout model to display each car and tried to make the ViewHolder class. Thanks in advice! My code:
Vehicle class:
public class Vehicle {
int anio, cv, kms, puertas;
double precio;
String combustible, foto, marca, modelo, palanca;
public Vehicle() {
} //setters and getters are too, but I omitted them
My cardview_template.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:padding="16dp"
>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cv"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/car_photo"
android:src="#drawable/ic_home_icon"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/marca"
android:text="Mercedes-Benz"
android:layout_toRightOf="#+id/car_photo"
android:layout_alignParentTop="true"
android:textSize="30sp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/kms"
android:text="128000"
android:layout_toRightOf="#+id/car_photo"
android:layout_below="#+id/marca"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/precio"
android:text="2018"
android:layout_toRightOf="#+id/car_photo"
android:layout_below="#+id/kms"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Part of the code that's in the method onCreate() in mi MainActivity:
I EDITED THE CODE. SEE IN THE EDIT BELOW
And finally, the class I used for the adapter. I think the problem is here:
I EDITED THE CLASS. SEE IN THE EDIT BELOW
EDIT
So following the advices, I changed the ListView with a RecyclerView, but it didn't work neither. I do not get any errors: CardViews simply do not appear in my RecyclerView.
Here's my new adapter class and the new code in the MainActivity onCreate()
Adapter:
public class VehicleListAdapter extends RecyclerView.Adapter<VehicleListAdapter.VehicleViewHolder> {
private ArrayList<Vehicle> mVehicleList;
public static class VehicleViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextView1;
public TextView mTextView2;
public TextView mTextView3;
public VehicleViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.car_photo);
mTextView1 = itemView.findViewById(R.id.marca);
mTextView2 = itemView.findViewById(R.id.modelo);
mTextView3 = itemView.findViewById(R.id.precio);
}
}
public VehicleListAdapter(ArrayList<Vehicle> vehicleslist) {
mVehicleList = vehicleslist;
}
#NonNull
#Override
public VehicleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//Links the cardview layout and prepares the ViewHolder
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_template, parent, false);
VehicleViewHolder vvh = new VehicleViewHolder(v);
return vvh;
}
#Override
public void onBindViewHolder(#NonNull VehicleViewHolder holder, int position) {
/*
* Links the layout elements with the variables in this class
* and put the object values in them
*/
Vehicle currentVehicle = mVehicleList.get(position);
//Uses Picasso librarie to set the image in the holder's ImageView
Picasso.get().load(currentVehicle.foto).into(holder.mImageView);
holder.mTextView1.setText(currentVehicle.getMarca());
holder.mTextView2.setText(currentVehicle.getModelo());
holder.mTextView3.setText(String.valueOf(currentVehicle.getPrecio()));
}
#Override
public int getItemCount() {
return mVehicleList.size();
}
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
(...)
//Prepares the recycler view and shows the data
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new VehicleListAdapter(vehiclesList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
EDIT2
Ok so I've come across a very strange thing. If I put a debug point anywhere in the onCreate() and then execute the app debugging, it works just fine. I'm completely lost.
If I don't do this, it shows like this:
It works both in the emulator and my actual phone.
first of all you should use recyclerView instead of ListView.
here is what you missed:
in the onCreate method replace this:
VehicleListAdapter adapter = new VehicleListAdapter(this, R.layout.content_main, vehiclesList);
with
VehicleListAdapter adapter = new VehicleListAdapter(this, R.layout.cardview_template, vehiclesList);
I know that the way I should do this is using a ListView in my layout, but I cant get the adapter to work.
Actually you need to know that Android apps are given with certain amount of RAM to work with, which will be less if you consider handling images. Hence using ListView is not suggested for Image Handling, specially for huge number of images. The solution to this is using RecyclerView, instead of ListView.
Also if you need to use RecyclerView, you need to extend RecyclerViewAdapter for the Adapter Class, which will have its own ViewHolder, subclass.
RecyclerView is easy to use, but difficult initially. After practising you will get the hang of it.
You can follow this youtube link RecyclerView + CardView - Part 1 - LAYOUTS AND CUSTOM OBJECTS - Android Studio Tutorial
If you still have some queries please comment, I would be happy to answer.
Activity class code:
conversationList = (ListView)findViewById(android.R.id.list);
ConversationArrayAdapter conversationArrayAdapter=new ConversationArrayAdapter(this, R.layout.conversation_list_item_format_left, conversationDetails);
conversationList.setAdapter(conversationArrayAdapter);
conversationList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Log.d("test","clicked");
}
});
The getView function in the Adapter class:
if (v == null) {
LayoutInflater vi = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(leftSideMessageNumber.equals(m.getTo())) {
v = vi.inflate(R.layout.conversation_list_item_format_left, null);
} else {
v = vi.inflate(R.layout.conversation_list_item_format_right, null);
}
}
Is there a problem with using two xmls while inflating?
I just found a solution from here, but by deep clicking.
If any row item of list contains focusable or clickable view then OnItemClickListener won't work.
The row item must have a param like
android:descendantFocusability = "blocksDescendants".
Here you can see an example of how your list item should look like.
Your list item xml should be...
row_item.xml (your_xml_file.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:descendantFocusability="blocksDescendants"
android:gravity="center_vertical" >
// your other widgets here
</LinearLayout>
The problem is that your layouts contain either focusable or clickable items.
If a view contains either focusable or clickable item the OnItemCLickListener won't be called.
Click here for more information.
Please post one of your layout xmls if that isn't the case.
For my lists, my rows have other things that can be clicked, like buttons, so doing a blanket blocksDescendants doesn't work. Instead I add a line in the button's xml:
android:focusable="false"
That keeps the buttons from blocking the clicks on the rows, but still lets the buttons take the clicks, too.
you need to do 2 steps in your listview_item.xml
set the root layout with: android:descendantFocusability="blocksDescendants"
set any focusable or clickable view in this item with:
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
Here is an example: listview_item.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="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:gravity="center_vertical"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants">
<RadioButton
android:id="#+id/script_name_radio_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#000"
android:padding="5dp"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
/>
</LinearLayout>
use the below code inside button tag in custom row layout of listview
android:focusable="false"
android:clickable="false"
I had the same problem and I just saw I had accidentally set:
#Override
public boolean isEnabled(int position)
{
return false;
}
on my CustomListViewAdapter class.
By changing this to:
return true;
I've managed to fix the problem.
Just in case if someone has done the same mistake...
Use android:descendantFocusability
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dip"
android:background="#color/light_green"
android:descendantFocusability="blocksDescendants" >
Add above in root layout
I solved it with the help of this answer
1.Add the following in Linear Layout of list_items.xml
android:descendantFocusability="blocksDescendants"
2.Child Views of LinearLayout in list_items.xml
android:focusable="false"
if you have textviews, buttons or stg clickable or selectable in your row view only
android:descendantFocusability="blocksDescendants"
is not enough. You have to set
android:textIsSelectable="false"
to your textviews and
android:focusable="false"
to your buttons and other focusable items.
Even I was having the same problem, I am having checkbox, did the following to masker itemClickListener work,
Added the following properties to the checkbox,
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
and ItemClickListner started working.
For detailed example you can go through the link,
http://knowledge-cess.com/android-itemclicklistner-with-checkbox-or-radiobutton/
Hope it helps Cheers!!
I had the same problem and tried all of the mentioned solutions to no avail. through testing i found that making the text selectable was preventing the listener to be called. So by switching it to false, or removing it my listener was called again.
android:textIsSelectable="false"
hope this helps someone who was stuck like me.
Add this in main Layout
android:descendantFocusability="blocksDescendants"
Write this code into every button,Textview,ImageView etc which have
onClick
android:focusable="false"
android:clickable="false"
Hope it will work.
Two awesome solutions were this, if your extending ListFragment from a fragment, know that mListView.setOnItemClickListener wont be called before your activity is created, this ensured it is set when activity has been created
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long rowId) {
// Do the onItemClick action
Log.d("ROWSELECT", "" + rowId);
}
});
}
While looking at the source code for ListFragment, I came across this
public class ListFragment extends Fragment {
...........................................
................................................
final private AdapterView.OnItemClickListener mOnClickListener
= new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
onListItemClick((ListView)parent, v, position, id);
}
};
................................................................
................................................................
public void onListItemClick(ListView l, View v, int position, long id) {
}
}
An onItemClickListener object is attached and it calls onListItemClick()
As such the other similar solution, which works in the exact same way is to override onListItemClick()
#Override
public void onListItemClick(ListView l, View v, int position, long rowId) {
super.onListItemClick(l, v, position, id);
// Do the onItemClick action
Log.d("ROWSELECT", "" + rowId);
}
in my case none of xml layout properties was not helpful.
I just add a single line of code like this:
convertView.setClickable(false);
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null || convertView.getTag() == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.my_layout_id, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
...
convertView.setClickable(false);
return convertView;
}
so basically it do the same thing as setting up properties in xml layout but it was only thing which works in my case.
It is not perfect timing but maybe it will helps somebody
Happy coding
I've tried all the above and NOTHING worked.
I solved the problem as follows:
First I define a custom Button called ListButton
public class ListButton extends android.widget.Button
{
private ButtonClickedListener clickListener;
public ListButton(Context context)
{
this(context, null);
}
public ListButton(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public ListButton(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
public void setClickListener(ButtonClickedListener listener) {
this.clickListener = listener;
}
#Override
public boolean isInTouchMode() {
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return false;
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_UP:
eventClicked();
break;
case MotionEvent.ACTION_CANCEL:
break;
case MotionEvent.ACTION_MOVE:
break;
default :
}
return true;
}
private void eventClicked() {
if (this.clickListener!=null) {
this.clickListener.ButtonClicked();
}
}
}
The XML looks like:
<dk.example.views.ListButton
android:id="#+id/cancel_button"
android:layout_width="125dp"
android:layout_height="80dp"
android:text="Cancel"
android:textSize="20sp"
android:layout_margin="10dp"
android:padding="2dp"
android:background="#000000"
android:textColor="#ffffff"
android:textStyle="bold"
/>
Then I define my own ButtonClicked Listener interface:
public interface ButtonClickedListener {
public void ButtonClicked();
}
Then I use my own listener just as if it was the normal OnClickListener:
final ListButton cancelButton = (ListButton) viewLayout.findViewById(R.id.cancel_button);
cancelButton.setClickListener(new ButtonClickedListener() {
#Override
public void ButtonClicked() {
//Do your own stuff here...
}
});
I had the same issue, I was using a style for my texts in the row layout that had the "focusable" attribute. It worked after I removed it.
In my case, I had to remove the next line from the Layout
android:clickable="true"
Android:autoText attribute also makes TextView auto focusable.
If you want to use both the simple click and long click on list view items better way to implement that would be to use context menu for long click. Avoid using setItemLongClickListener especially if you have multiple row layouts for your listview.
Faced same problem, tried for hours. If you have tried all of the above than try changing layout_width of Listview and list item to match_parent from wrap_content.
All of the above failed for me. However, I was able to resolve the problem (after many hours of banging my head - Google, if you're listening, please consider fixing what I encountered below in the form of compiler errors, if possible)
You really have to be careful of what android attributes you add to your xml layout here (in this original question, it is called list_items.xml). For me, what was causing the problem was that I had switched from an EditText view to a TextView and had leftover attribute cruft from the change (in my case, inputType). The compiler didn't catch it and the clickability just failed when I went to run the app. Double check all of the attributes you have in your layout xml nodes.
private AdapterView.OnItemClickListener onItemClickListener;
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
.......
final View view = convertView;
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(null, view, position, -1);
}
}
});
return convertView;
}
public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
Then in your activity, use adapter.setOnItemClickListener() before attaching it to the listview.
Copied from github its worked for me
The thing that worked for me was to add the below code to every subview inside the layout of my row.xml file:
android:focusable="false"
android:focusableInTouchMode="false"
So in my case:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:focusable="false"
android:focusableInTouchMode="false"
android:id="#+id/testingId"
android:text="Name"
//other stuff
/>
<TextView
android:focusable="false"
android:focusableInTouchMode="false"
android:id="#+id/dummyId"
android:text="icon"
//other stuff
/>
<TextView
android:focusable="false"
android:focusableInTouchMode="false"
android:id="#+id/assignmentColor"
//other stuff
/>
<TextView
android:focusable="false"
android:focusableInTouchMode="false"
android:id="#+id/testID"
//other stuff
/>
<TextView
android:focusable="false"
android:focusableInTouchMode="false"
android:text="TextView"
//other stuff
/>
</android.support.constraint.ConstraintLayout>
And this is my setOnItemClickListener call in my Fragment subclass:
CustomListView = (PullToRefreshListCustomView) layout.findViewById(getListResourceID());
CustomListView.setAdapter(customAdapter);
CustomListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("Testing", "onitem click working");
// other code
}
});
I got the answer from here!
Had the same problem with onClick. The solution was to remove from the xml the following
android:tooltipText=""
I solved the problem by removing the clickable views from the list.
I know there are dozens similar post, but it looks to me everything is correct here:
The custom widget:
public class DoubleTextItem extends LinearLayout {
private TextView txtMain;
private TextView txtDescription;
public DoubleTextItem(Context context) {
super(context);
}
public DoubleTextItem(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
((Activity)getContext()).getLayoutInflater().inflate(R.layout.widget_double_text_item, this);
setupViewItems();
}
private void setupViewItems() {
txtMain = (TextView) findViewById(R.id.txtMain);
txtDescription = (TextView) findViewById(R.id.txtDecription);
}
public void setDescription(String text) {
txtDescription.setText(text);
}
}
The custom widget layout xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/txtMain"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txtDecription"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
ANd here inside an activity function i get a casting error,
LayoutInflater inflater = LayoutInflater.from(this);
DoubleTextItem item = (DoubleTextItem) inflater.inflate(R.layout.widget_double_text_item, layout);
item.setText(som-txt);
item.setDescription("#"+athlete.getString("position"));
Here, the root View is a LinearLayout but you try to cast it your custom class:
DoubleTextItem item = (DoubleTextItem) inflater.inflate(R.layout.widget_double_text_item, layout);
The standard advice is:
All DoubleTextItems are LinearLayouts, but not all LinearLayouts are DoubleTextItems.
Meaning you cannot downcast objects from a LinearLayout to a DoubleTextItem, there are too many assumptions and Java won't let you do it.
If you want a DoubleTextItem in your layout you need to use:
<your.package.name.DoubleTextItem
... />
(Also, calling inflate inside onFinishInflate() seems a little silly especially since you don't save the inflated item... If you want to inflate a different layout, don't inflate the first one.)
Overall it looks like you are trying to recreate the now deprecated TwoLineListItem, perhaps you can learn some pointers from it's source code (or just use the TwoLineListItem.)
I have a problem with adding a listview as a header in my listview (go go redundancy). The code is working, however only the first item shows up in the header. The body looks fine.
listView = (ListView) findViewById(R.id.default_list_view);
header = (ListView) getLayoutInflater().inflate(R.layout.savings_overview_header_list, null, false);
HeaderAdapter hAdapter = new HeaderAdapter(getLayoutInflater());
hAdapter.addItem("1");
hAdapter.addItem("2");
hAdapter.addItem("3");
header.setAdapter(hAdapter);
for (Policy p : saving.getPolicies()) {
adapter.addItem(p);
}
listView.addHeaderView(header);
listView.setAdapter(adapter);
headerView:
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/default_list_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#00000000"
android:divider="#drawable/list_divider"
android:dividerHeight="2px"
android:fadingEdge="none"
android:fitsSystemWindows="true"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false"
android:listSelector="#drawable/list_item_background_selected"
>
</ListView>
I have tried wrapping the ListView in a vertical LinearLayout but no cigar there either :(
hAdapter
private static class HeaderAdapter extends BaseAdapter {
private final LayoutInflater inflater;
protected ArrayList<String> data = new ArrayList<String>();
public HeaderAdapter(LayoutInflater inflater) {
this.inflater = inflater;
}
public void addItem(String s) {
data.add(s);
}
public View getView(int position, View convertView, ViewGroup parent) {
final PolicyViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.savings_overview_header_item, parent, false);
holder = new PolicyViewHolder();
holder.header = (TextView) convertView.findViewById(R.id.list_item_header);
holder.subHeader = (TextView) convertView.findViewById(R.id.list_item_subheader);
holder.img = (ImageView) convertView.findViewById(R.id.list_item_img);
convertView.setTag(holder);
} else {
holder = (PolicyViewHolder) convertView.getTag();
}
String s = data.get(position);
holder.header.setText(s);
holder.subHeader.setText(s);
holder.img.setImageResId(R.drawable.test);
return convertView;
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
private static class PolicyViewHolder {
TextView header;
TextView subHeader;
ImageView img;
}
}
header_item
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<ImageView
android:id="#+id/list_item_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="#drawable/ic_launcher"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:layout_marginLeft="5dp"
android:layout_toLeftOf="#+id/list_item_value"
android:layout_toRightOf="#+id/header_image"
android:orientation="vertical" >
<TextView
android:id="#+id/list_item_header"
style="#style/header_list_header"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/list_item_subheader"
style="#style/list_header_sub_header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="sub header" />
</LinearLayout>
</RelativeLayout>
i have tried to wrap a linearlayout="vertical" around this one as well
You have to tell the parent view how to stack your elememnts. This is necessary for parents like a LinearLayout. If you're going to have such an adapter, you need to have a parent to contain these things, UNLESS its a single view.
Update
Whenever you want to do processing with the views in a ListView you
need to create a custom adapter that will handle your logic
implementation and pass that information to the views as necessary.
A custom adater would inflate the views piece by piece, this can be
dynamic of fixed.
I suspect that your problem relates to Android simply not knowing how to handle the two levels of "scrollability" this design implies. Think about it - If the user drags over the header, how is Android supposed to know whether they mean to scroll the outer list or the list within the header? I once recall Romain Guy making the same point about placing ListViews inside ScrollViews, it's slightly meaningless.
What's probably happening is that Android makes the header big enough to simply display a single header list item and it assumes any dragging gesture by the user should apply to the outer list.
Generally, I think what you've described sounds like a bad design choice and you need to take a step back.
What functionally do you want this UI to do?
If it's simply that you want to display two sets of content within a single list, then this is a problem you need to solve within the ListAdapter implementation you're using. e.g. Take a look Jeff Sharkey's blog post on his SeparatedListAdapter.
Make a LinearLayout with vertical orientation and add both ListViews there. That should fix your hiccup.
Cheers.