I want create a horizontal recycle view and i writed this code:
in main activity xml
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" >
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
And this is adapter class
public class AdapterNote extends ArrayAdapter<StructCategory> {
public AdapterNote(ArrayList<StructCategory> array) {
super(G.context, R.layout.adapter_category, array);
}
private static class ViewHolder {
public TextView txtTitle;
public ViewHolder(View view) {
txtTitle = (TextView) view.findViewById(R.id.cat_txt);
}
public void fill(final ArrayAdapter<StructCategory> adapter, final StructCategory item, final int position) {
txtTitle.setText(item.title);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
StructCategory item = getItem(position);
if (convertView == null) {
convertView = G.inflater.inflate(R.layout.adapter_category, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}}
In the MainClass setadapter
setadapter function has error :
The type android.support.v4.view.NestedScrollingChild2 cannot be resolved. It is indirectly referenced from required .class files
I imported support v4 api 20 and v7compat v20 and v7 recycleview api 20
but dont work my code
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView myList = (RecyclerView) findViewById(R.id.my_recycler_view);
myList.setLayoutManager(layoutManager);
adapter = new AdapterNote(G.tasksCategory);
myList.setAdapter(adapter);
and i create xml for adapter class:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" android:padding="8dip" android:gravity="right">
<TextView
android:id="#+id/cat_txt"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="#drawable/category_txt"
android:gravity="center_vertical|center"
android:text="TextView"
android:textColor="#000" />
</LinearLayout>
please help me for this problem
As you are using RecyclerView, extends your adapter class by RecyclerView.Adapter<>.
Please refer this : https://www.google.com/amp/s/www.androidhive.info/2016/01/android-working-with-recycler-view/amp/
I edit my code Like recycleview adapter example:
please check my code and fix it
Error txt on Classname and MyViewHolder :
The hierarchy of the type AdapterCategory is inconsistent
in the problem section show this error:
The project was not built since its build path is incomplete. Cannot find the class file for android.support.v4.view.NestedScrollingChild2. Fix the build path then try building this project
public class AdapterCategory extends RecyclerView.Adapter<AdapterCategory.MyViewHolder> {
private ArrayList<StructCategory> categoryList;
private ItemClickListener mClickListener;
AdapterCategory(Context context, ArrayList<StructCategory> categoryList) {
G.inflater = LayoutInflater.from(context);
this.categoryList = categoryList;
}
// inflates the row layout from xml when needed
#Override
#NonNull
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = G.inflater.inflate(R.layout.adapter_category, parent, false);
return new MyViewHolder(view);
}
// binds the data to the view and textview in each row
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
StructCategory hList = categoryList.get(position);
holder.myTextView.setText(hList.title);
}
// total number of rows
#Override
public int getItemCount() {
return categoryList.size();
}
// stores and recycles views as they are scrolled off screen
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
MyViewHolder(View itemView) {
super(itemView);
myTextView = (TextView) itemView.findViewById(R.id.cat_txt);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null)
mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public StructCategory getItem(int id) {
return categoryList.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}}
Related
I want to create tags using RecyclerView that can be selected to produce results.
What I want to achieve is when I tap on Books TextView on the top-right must change to Books immediately. In my case when I tap on Books it just stays in Art and it replaces Art with Books only when I replace my fragments. I also highlight buttons when clicked (changing border from grey to black) but after changing fragments highlights return back to Art again. Shortly I want to highlight button when clicked and change TextView content based on clicked button text. I partly achieved it by using interfacews but didn't get what I wanted. I provided codes below:
TrendCategoryTagsAdapter.java:
public class TrendCategoryTagsAdapter extends FirestoreRecyclerAdapter<CategorySelection, TrendCategoryTagsAdapter.TrendCategoryTagsHolder> {
Context context;
onCategoryTagClicked onCategoryTagClicked;
int row_index;
public TrendCategoryTagsAdapter(#NonNull FirestoreRecyclerOptions<CategorySelection> options, Context context, com.rajabmammadli.paragrafredesign.Interface.onCategoryTagClicked onCategoryTagClicked) {
super(options);
this.context = context;
this.onCategoryTagClicked = onCategoryTagClicked;
}
#Override
protected void onBindViewHolder(#NonNull final TrendCategoryTagsHolder holder, final int position, #NonNull CategorySelection model) {
holder.categoryNameText.setText(model.getCategoryName());
holder.categoryNameContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
row_index = position;
notifyDataSetChanged();
}
});
if (row_index == position) {
holder.categoryNameContainer.setBackground(ContextCompat.getDrawable(context, R.drawable.black_rounded_bg));
onCategoryTagClicked.onTagClick(holder.categoryNameText.getText().toString());
} else {
holder.categoryNameContainer.setBackground(ContextCompat.getDrawable(context, R.drawable.grey_rounded_bg));
}
}
#NonNull
#Override
public TrendCategoryTagsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.trendcategory_cell, parent, false);
return new TrendCategoryTagsAdapter.TrendCategoryTagsHolder(v);
}
public static class TrendCategoryTagsHolder extends RecyclerView.ViewHolder {
RelativeLayout categoryNameContainer;
TextView categoryNameText;
public TrendCategoryTagsHolder(#NonNull View itemView) {
super(itemView);
categoryNameContainer = itemView.findViewById(R.id.categoryNameContainer);
categoryNameText = itemView.findViewById(R.id.categoryNameText);
}
}
}
trendcategory_cell.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<RelativeLayout
android:id="#+id/categoryNameContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/grey_rounded_bg">
<TextView
android:id="#+id/categoryNameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/gilroyregular"
android:padding="15dp"
android:text="categoryname"
android:textColor="#android:color/black" />
</RelativeLayout>
</RelativeLayout>
TrendingFragment.java:
public class TrendingFragment extends Fragment implements onCategoryTagClicked {
RecyclerView trendingCategoryRV;
TextView noPostTV, selectedCategoryText;
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference categoryRef;
String selectedCategory = "Art";
TrendCategoryTagsAdapter trendCategoryTagsAdapter;
public TrendingFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_trending, container, false);
trendPostRV = view.findViewById(R.id.trendPostRV);
trendingCategoryRV = view.findViewById(R.id.trendingCategoryRV);
noPostTV = view.findViewById(R.id.noPostTV);
selectedCategoryText = view.findViewById(R.id.selectedCategoryText);
selectedCategoryText.setText(selectedCategory);
setUpTrendCategoryTagsRV();
setUpTrendingPostRV();
// Inflate the layout for this fragment
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
trendCategoryTagsAdapter.startListening();
}
#Override
public void onDestroyView() {
super.onDestroyView();
trendCategoryTagsAdapter.stopListening();
}
private void setUpTrendCategoryTagsRV() {
categoryRef = db.collection("Categories");
Query query = categoryRef.orderBy("categoryName", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<CategorySelection> options = new FirestoreRecyclerOptions.Builder<CategorySelection>()
.setQuery(query, CategorySelection.class)
.build();
trendCategoryTagsAdapter = new TrendCategoryTagsAdapter(options, getContext(), this);
trendingCategoryRV.setNestedScrollingEnabled(false);
final LinearLayoutManager trendingTagsLM = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
trendingCategoryRV.setLayoutManager(trendingTagsLM);
trendingCategoryRV.setAdapter(trendCategoryTagsAdapter);
trendCategoryTagsAdapter.notifyDataSetChanged();
}
#Override
public void onTagClick(String categoryName) {
selectedCategory = categoryName;
}
}
Any help will be appreciated. Thanks in advance
I have a list of Message objects. Message is an abstract class, with two subclasses: TextMessage and ImageMessage
I would like to display the messages in a scrollable list, based on the type of the message. How is it possible to create a custom view/fragment with an abstract class as parameter, and create a TextView/ImageView inside it according to the actual subclass?
I've read the official android guide, but I still have no idea, how to do this.
Ok, So since a RecyclerView is the recommended view for a list of items with an undefined size, I'm gonna assume your want to use a RecyclerView for this.
If you then follow the sample code to make such a view, then you could make your Message class declare an abstract getViewType and bindToView method as follows:
Message.java
public abstract class Message {
public abstract int getViewType();
public abstract void bindToView(View messageView);
public enum TYPE {
TextMessage,
ImageMessage
}
public static View createView(int typeOrdinal, Context context) {
switch (TYPE.values()[typeOrdinal]) {
case TextMessage:
return TextMessage.createNewView(context);
case ImageMessage:
return ImageMessage.createNewView(context);
default:
throw new RuntimeException("Incorrect typeOrdinal: " + typeOrdinal);
}
}
}
TextMessage.java
public class TextMessage extends Message {
public static TextView createNewView(Context context) {
return new TextView(context);
}
#Override
public void bindToView(View messageView) {
((TextView) messageView).setText("some specific text");
}
#Override
int getViewType() {
return TYPE.TextMessage.ordinal();
}
}
ImageMessage.java
public class ImageMessage extends Message {
public static ImageView createNewView(Context context) {
return new ImageView(context);
}
#Override
public void bindToView(View messageView) {
Bitmap forExampleSomeBitmap = null; // TODO implement
((ImageView) messageView).setImageBitmap(forExampleSomeBitmap);
}
#Override
int getViewType() {
return TYPE.ImageMessage.ordinal();
}
}
And then With all the rest of the code from that google sample code unchanged, your RecyclerView.Adapter could then look like this:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Message[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public View messageView;
public MyViewHolder(View v) {
super(v);
messageView = v;
}
}
#NonNull
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(Message.createView(viewType, parent.getContext()));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
mDataset[position].bindToView(holder.messageView);
}
#Override
public int getItemViewType(int position) {
return mDataset[position].getViewType();
}
#Override
public int getItemCount() {
return mDataset.length;
}
}
If you want to know more about how the recyclerview works, why it recycles views, then I would recommend this arcticle.
1 : Create new project -> select Basic Activity
there is to fragment inside your activity and a button to switch between fragment A to B
2 : create a RecyclerView resource in SecondFragment (fragment B )
add the following line into second fragment :
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="409dp"
android:layout_height="460dp"
android:layout_marginStart="1dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="1dp"
android:visibility="visible"
app:layout_constraintBottom_toTopOf="#+id/button_second"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
3 : create a frame layout with textview
go to /res/layout/newlayout/layoutresource file and create an framlayout
inside the layout replace this codes
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<TextView
android:id="#+id/randomText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="This is some temp text" />
</FrameLayout>
4: Add RecyclerView in Fragment
go to second fragment and paste all of these
public class SecondFragment extends Fragment {
// Add RecyclerView member
private RecyclerView recyclerView;
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_second, container, false);
// Add the following lines to create RecyclerView
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
recyclerView.setAdapter(new RandomNumListAdapter(1234));
return view;
}
5 : create a class Viewholder for recyclerview
like this :
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
private TextView view;
public RecyclerViewHolder(#NonNull View itemView) {
super(itemView);
view = itemView.findViewById(R.id.randomText);
}
public TextView getView(){
return view;
}
}
6 : Create ListAdapter
public class RandomNumListAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
private Random random;
public RandomNumListAdapter(int seed) {
this.random = new Random(seed);
}
#Override
public int getItemViewType(final int position) {
return R.layout.frame_textview;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false);
return new RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
holder.getView().setText(String.valueOf(random.nextInt()));
}
#Override
public int getItemCount() {
return 100;
}
}
you can replace your items with random numbers .
I'm trying to implement button on each row in ListView, but I saw many topics and I don't succeeded to add code to mine. Here is my MainActivity :
public class MainActivity extends AppCompatActivity {
private ArrayAdapter<String> itemsAdapter;
private ArrayList<String> items;
private ImageButton formButton;
private ListView lvMain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
commonFunction();
}
public void commonFunction() {
lvMain = (ListView) findViewById(R.id.lvMain);
items = new ArrayList<String>();
readItems();
itemsAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
items);
lvMain.setAdapter(itemsAdapter);
formButton = (ImageButton) findViewById(R.id.btnPlus);
formButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setLayoutActivity();
}
});
}
}
Here is my activity_main.xml :
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lvMain"
android:layout_above="#+id/btnPlus" />
<ImageButton
android:layout_width="match_parent"
android:layout_height="65dp"
android:id="#+id/btnPlus"
android:layout_alignParentBottom="true"
app:srcCompat="#mipmap/ic_plus_foreground" />
Does someone any idea how to do ?
Create custom adapter with custom row layout file and add button on that row file and bind it to List/Recycler view. So it will inflate in all row.
Add below code in row_list.xml file.
<ImageButton
android:layout_width="match_parent"
android:layout_height="65dp"
android:id="#+id/btnPlus"
android:layout_alignParentBottom="true"
app:srcCompat="#mipmap/ic_plus_foreground" />
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
private ArrayList data;
private static LayoutInflater inflater = null;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(ArrayList d) {
/********** Take passed values **********/
data = d;
/*********** Layout inflater to call external xml layout () ***********/
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
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;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder {
public ImageButton button;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.row_list, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.button = (ImageView) vi.findViewById(R.id.btnPlus);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Button click
}
});
return vi;
}}
Hope it will solve problem.
Happy coding!!
Crate custom adapter and bind it with the ListView.
Inflate custom layout for each row in the adapter.
You can put your button in the custom layout file.
public class CustomAdapter extends ArrayAdapter<String> {
private Context context;
private int singleRowLayoutId;
public CustomAdapter(Context context, int singleRowLayoutId, String []titles, String []desc, int []images ) {
super(context, singleRowLayoutId,titles);
this.context=context;
this.singleRowLayoutId=singleRowLayoutId; //custom row layout for list view item
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row=convertView;
CustomViewHolder holder=null;
if(row==null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//view object of single row of list view
row = inflater.inflate(singleRowLayoutId, parent, false);
//by using holder, we make sure that findViewById() is not called every time.
holder=new CustomViewHolder(row);
row.setTag(holder);
}
else
{
holder=(CustomViewHolder)row.getTag();
}
return row;
}
private class CustomViewHolder {
private ImageButton mbtn;
CustomViewHolder(View view)
{
mbtn=(ImageButton)view.findViewById(R.id.btn);
mbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle button click here
}
});
}
}
I think that this is what you need - create a separate layout for the rows in the list view. Then create a custom adapter, where you are adding this layout as row layout and then set this adapter to your list view. Here are the details with examples:
Android custom Row Item for ListView
I am new for Android development.
I was trying to implement a custom ArrayAdapter to accept custom object in Android Studio.
I have referenced the source code from some tutorial, but my screen output was improper that the custom object only fill in the TextView which link with the textViewResourceId of ArrayAdapter , but not the custom object's properties fill in all EditText in the layout appropriately.
I tried to remove textViewResourceId parameter in the constructor of ArrayAdapter to fix the problem, but Android Studio returned error - You must supply a resource ID for a TextView
I want the properties of custom object fill in all EditText and no error message be returned, can anyone give me a hint?
Here is my layout:
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/row_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
<EditText
android:id="#+id/row_no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="1dp"
android:layout_gravity="center_horizontal"
android:background="#color/colorWhite"/>
<EditText
android:id="#+id/row_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="1dp"
android:layout_gravity="center_horizontal"
android:background="#color/colorWhite"/>
</LinearLayout>
Here is my custom object:
Row.java
public class Row
{
public int RowNo;
public String RowText;
public Row(int no, String text)
{
this.RowNo = no;
this.RowText = text;
}
}
Here is my custom ArrayAdapter:
RowAdapter.java
public class RowAdapter extends ArrayAdapter<Row> {
private final Activity _context;
private final ArrayList<Row> rows;
static class ViewHolder
{
EditText RowNo;
EditText RowText;
}
public RowAdapter(Activity context, ArrayList<Row> rows)
{
super(context,R.layout.row_layout, R.id.row_id ,rows);
this._context = context;
this.rows = rows;
}
public View GetView(int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
if(convertView == null)
{
LayoutInflater inflater = _context.getLayoutInflater();
convertView = inflater.inflate(R.layout.row_layout,parent,false);
holder = new ViewHolder();
holder.RowNo = (EditText)convertView.findViewById(R.id.row_no);
holder.RowText = (EditText)convertView.findViewById(R.id.row_text);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.RowNo.setText(rows.get(position).RowNo);
holder.RowText.setText(rows.get(position).RowText);
return convertView;
}
}
Here is my Activity class:
RowActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_list_page);
listView = (ListView)findViewById(R.id.list_view);
ArrayList<Row> rows = new ArrayList<Row>();
rows.add(new Row(1,"Test"));
rows.add(new Row(2,"Test"));
rows.add(new Row(3"Test"));
RowAdapter adapter = new RowAdapter(this,rows);
listView.setAdapter(adapter);
}
Here is working adapter code
public class RowAdapter extends ArrayAdapter<Row> {
private final Activity _context;
private final ArrayList<Row> rows;
public class ViewHolder
{
EditText RowNo;
EditText RowText;
}
public RowAdapter(Activity context, ArrayList<Row> rows)
{
super(context,R.layout.row_layout, R.id.row_id ,rows);
this._context = context;
this.rows = rows;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
if(convertView == null)
{
LayoutInflater inflater = _context.getLayoutInflater();
convertView = inflater.inflate(R.layout.row_layout,parent,false);
holder = new ViewHolder();
holder.RowNo = (EditText)convertView.findViewById(R.id.row_no);
holder.RowText = (EditText)convertView.findViewById(R.id.row_text);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.RowNo.setText(""+rows.get(position).RowNo);
holder.RowText.setText(rows.get(position).RowText);
return convertView;
}
}
Your getting exception at holder.RowNo.setText(rows.get(position).RowNo);
so replace it with
holder.RowNo.setText(""+rows.get(position).RowNo);
Change with below code:-
RowAdapter.java
public class RowAdapter extends BaseAdapter {
private final Context _context;
private final ArrayList<Row> rows;
public RowAdapter(Context context, ArrayList<Row> rows)
{
this._context = context;
this.rows = rows;
}
#Override
public int getCount() {
return rows.size();
}
#Override
public Object getItem(int position) {
return rows;
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView=inflater.inflate(R.layout.row_layout, null,true);
EditText RowNo = (EditText) rowView.findViewById(R.id.row_no);
EditText RowText = (EditText) rowView.findViewById(R.id.row_text);
RowNo.setText(rows.get(position).RowNo);
RowText.setText(rows.get(position).RowText);
return rowView;
}
}
public View getView (int position, View convertView, ViewGroup parent)
This method is called to get view object.
In your code there is GetView, not getView
change your
public View GetView(int position, View convertView, ViewGroup parent)
with
#Override
public View getView(int position, View convertView, ViewGroup parent)
and
holder.RowNo.setText(rows.get(position).RowNo);
with
holder.RowNo.setText(""+rows.get(position).RowNo);
I'm trying to make a task manager, and I only have one problem. I have a listview that gets inflated. All the elements in the listview are correct. The problem is that when I select an item, the listview will select another item away. I've heard listviews repopulate the list as it scrolls down to save memory. I think this may be some sort of problem. Here is a picture of the problem.
If i had more apps loaded, then it would continue to select multiple at once.
Here is the code of my adapter and activity and XML associated
public class TaskAdapter extends BaseAdapter{
private Context mContext;
private List<TaskInfo> mListAppInfo;
private PackageManager mPack;
public TaskAdapter(Context c, List<TaskInfo> list, PackageManager pack) {
mContext = c;
mListAppInfo = list;
mPack = pack;
}
#Override
public int getCount() {
return mListAppInfo.size();
}
#Override
public Object getItem(int position) {
return mListAppInfo.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
//System.out.println("Setting LayoutInflater in TaskAdapter " +mContext +" " +R.layout.taskinfo +" " +R.id.tmbox);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
final CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
if(v.isSelected())
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
}
else
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
}
}
});
return convertView;
public class TaskManager extends Activity implements Runnable
{
private ProgressDialog pd;
private TextView ram;
private String s;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.taskpage);
setTitleColor(Color.YELLOW);
Thread thread = new Thread(this);
thread.start();
}
#Override
public void run()
{
//System.out.println("In Taskmanager Run() Thread");
final PackageManager pm = getPackageManager();
final ListView box = (ListView) findViewById(R.id.cBoxSpace);
final List<TaskInfo> CK = populate(box, pm);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
ram.setText(s);
box.setAdapter(new TaskAdapter(TaskManager.this, CK, pm));
//System.out.println("In Taskmanager runnable Run()");
endChecked(CK);
}
});
handler.sendEmptyMessage(0);
}
Taskinfo.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/tmImage"
android:layout_width="48dp"
android:layout_height="48dp"
android:scaleType="centerCrop"
android:adjustViewBounds="false"
android:focusable="false" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tmbox"
android:lines="2"/>
</LinearLayout>
Taskpage.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="vertical">
<ListView
android:id="#+id/cBoxSpace"
android:layout_width="wrap_content"
android:layout_height="400dp"
android:orientation="vertical"/>
<TextView
android:id="#+id/RAM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp" />
<Button
android:id="#+id/endButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="End Selected Tasks" />
</LinearLayout>
Any ideas for what reason mutliple items are selected with a single click would be GREATLY appreciated. I've been messing around with different implementations and listeners and listadapters but to no avail.
I think the point is you only save checking state in the view(v.setSelected).
And you reuse these view, so its checkbox is always not change its state.
You can create a state array to save every checking state of every TaskInfo, and check this array when you create a view.
for example
// default is false
ArrayList<Boolean> checkingStates = new ArrayList<Boolean>(mListAppInfo.size());
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
final CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
checkBox.setChecked(checkingStates.get(position));
convertView.setSelected(checkingStates.get(position));
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(v.isSelected())
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
checkingStates.get(position) = false;
}
else
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
checkingStates.get(position) = true;
}
}
});
return convertView;
}
I'm not 100% sure what you are trying to do, but part of your problem might be related to the condition in your onClick method:
if(v.isSelected())
I think you want that to read
if(v.isChecked())
isSelected is inherited from View, and it means something different from isChecked
Also, the whether the CheckBox is checked or not is independent from your data model since it is a recycled view. Your CheckBox should be checked based on entry (I'm assuming your TextInfo class has an isChecked() method that returns a boolean:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
//System.out.println("Setting LayoutInflater in TaskAdapter " +mContext +" " +R.layout.taskinfo +" " +R.id.tmbox);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
checkBox.setChecked(entry.isChecked());
}
I don't think you need the View.OnClickListener you are attaching to convertView. You should handle that in the OnItemClickListener attached to the ListView. Assuming your ListView is called listView and TaskInfo instances have setChecked and isChecked methods:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
entry = mListAppInfo.get(position);
entry.setChecked(!entry.isChecked());
}
});
First of all don't set the list checked or unchecked on view position.
because view position means only visible items position in your listview but you would like to set checked or uncheked status on a particular list item.
That's why this problem arises in your code.
You have the need to set the items checked and unchecked on your custom arraylist getter setter like the code i have attached below:
package com.app.adapter;
public class CategoryDynamicAdapter {
public static ArrayList<CategoryBean> categoryList = new ArrayList<CategoryBean>();
Context context;
Typeface typeface;
public static String videoUrl = "" ;
Handler handler;
Runnable runnable;
// constructor
public CategoryDynamicAdapter(Activity a, Context context, Bitmap [] imagelist,ArrayList<CategoryBean> list) {
this.context = context;
this.categoryList = list;
this.a = a;
}
// Baseadapter to the set the data response from web service into listview.
public BaseAdapter mEventAdapter = new BaseAdapter() {
#Override
public int getCount() {
return categoryList.size();
}
#Override
public Object getItem(int position) {
return categoryList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
class ViewHolder {
TextView title,category,uploadedBy;
ImageView image;
RatingBar video_rating;
Button report_video ,Flag_video;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder vh = null ;
if(convertView == null) {
vh = new ViewHolder();
convertView = LayoutInflater.from(context).inflate (R .layout.custom_category_list_layout,null,false);
vh.title = (TextView) convertView .findViewById (R.id.title);
vh.image = (ImageView) convertView.findViewById(R.id.Imagefield);
convertView.setTag(vh);
}
else
{
vh=(ViewHolder) convertView.getTag();
}
try
{
final CategoryBean Cb = categoryList.get(position);
//pay attention to code below this line i have shown here how to select a listview using arraylist getter setter objects
String checkedStatus = Cb.getCheckedStringStaus();
if(checkdStatus.equal("0")
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
}
else ////checkdStatus.equal("1")
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
}
catch (Exception e)
{
e.printStackTrace();
}