ListView Shows Items Mulitple Times Android Java - java

Stackflowers!
I've a problem with my listview. I load data(text) from a webpage/url and load them in my listview. I have a title and a blog with the text (sometimes more blogs as shown below..).
But the problem is, he loads only 1 time the title, but shows it multiply times. (Shown below).
BBC News:
BBC Newsnight's political editor Emily Maitlis told the programme that she had spoken to the lawyers who are preparing the test case for the female prisoner, who is identified as BGJ and is serving a life sentence.
BBC News:
"She is an epilepsy sufferer, very highly qualified and she has said her life is in despair without access to these books, which have really been taking her through this life sentence that she will serve," she said.
BBC News:
Lawyers for the woman argue that the effects of the policy are particularly hard felt by women who depend on what they receive from the outside world to keep them motivated.
BBC News:
The MoJ said the lawyers had no grounds for their case because they had run out of time to make it.
How can I filter my listview? For only 1 title?
Thanks,
P.S. If somebody need some code, please ask! Thank you.
Update:
Part of code:
public class second_activity extends Activity {
private List<post_second> my_post_second = new ArrayList<post_second>();
String title[] = new String[counter_title];
String blog[] = new String[counter_blog];
private void populate_post_list() {
for (int i = 0; i < 1; i++) {
for (int j = 0; j < counter_blog_stop; j++) {
my_post_second.add(new post_second(title[i], blog[j]));
}
}
}
private void populate_list_view() {
ArrayAdapter<post_second> adapter = new my_list_adapter_second();
global.list = (ListView) findViewById(R.id.post_second_list_view);
global.list.setAdapter(adapter);
}
private class my_list_adapter_second extends ArrayAdapter<post_second> {
public my_list_adapter_second() {
super(second_activity.this, R.layout.item_view_second, my_post_second);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View item_view_second = convertView;
if (item_view_second == null) {
item_view_second = getLayoutInflater().inflate(R.layout.item_view_second, parent, false);
}
// Find the Post to work with.
post_second current_post = my_post_second.get(position);
// Title:
TextView title_text = (TextView) item_view_second.findViewById(R.id.item_title);
title_text.setText(Html.fromHtml(current_post.get_title()));
// Blog:
TextView blog_text = (TextView) item_view_second.findViewById(R.id.item_blog);
blog_text.setText(Html.fromHtml(current_post.get_blog()));
return item_view_second;
}
}

Here you have added the title for each and every row.
for (int i = 0; i < 1; i++) {
for (int j = 0; j < counter_blog_stop; j++) {
my_post_second.add(new post_second(**title[i]**, blog[j]));
}
}
So you can hide the title if the row is not the first one by
// Title:
TextView title_text = (TextView) item_view_second.findViewById(R.id.item_title);
if(position == 0){
title_text.setVisibility(View.VISIBLE);
title_text.setText(Html.fromHtml(current_post.get_title()));
}
else{
title_text.setVisibility(View.GONE);
}

Its better you can use Expandable ListView for your case. Else you can hide the title layout in your adapter wherever you don't need of it. We can't conclude until you post your code. Better you can post your code.

Related

How To Check if all ImageView inside GridLayout is not Empty?

I'm trying to make a tictactoe game using Android Studio. I already write a code to set the button visibility when someone is win (and it work). I also want the game to show "play again" button when the board is full but no one win (tie). How do i do that.
Here's what I'm trying to code:
public boolean checkGameState () {
boolean isBoardFull = false;
androidx.gridlayout.widget.GridLayout gridLayout = findViewById(R.id.gridLayout);
for (int i = 0; i < gridLayout.getChildCount(); i++) {
ImageView reset = (ImageView) gridLayout.getChildAt(i);
if(reset.getDrawable() != null) {
isBoardFull = true;
}
}
return isBoardFull;
}
Here's a screenshot of what the game look like:
as you can see in the image, the "Play again" button is visible even though the game hasn't been finished yet. The button will show if the someone is win or tie (the board is full).
There is slight mistake with your condition as once it found drawable it marks as isBoardFull as true, Which is wrong as all child haven't been checked yet so marking isBoardFull as true at this stage is wrong.
You can do like following:
public boolean checkGameState () {
boolean isBoardFull = true; // first mark it as full
androidx.gridlayout.widget.GridLayout gridLayout = findViewById(R.id.gridLayout);
for (int i = 0; i < gridLayout.getChildCount(); i++) {
ImageView reset = (ImageView) gridLayout.getChildAt(i);
if(reset.getDrawable() == null) {
isBoardFull = false; // if drawable not found that means it's not full
}
}
return isBoardFull;
}
So now first it will mark board as full but once any drawable is found as null it will mark board as empty.
I think you should initialize a variable isEveryChildChecked = true before iterating the gridLayout child.
While iterating the children, if a grid is not checked, set the field isEveryChildChecked = false.
Then after iteration, check the field isEveryChildChecked, If it is true, you can display play again else do nothing or hide the Play again button.

Adding data to my ArrayAdapter, Iam using RecyclerView to display this information

I have been tasked with making an app in android studio. This app will display courses in a small department at a local college. so who ever uses the app can navigate to a list of 20 courses, pick one course and get some information about it.
I have most of the app sorted but I am having trouble adding the 20 courses to my RecyclerView. I am trying to use an ArrayAdapter but I don't know how to add the 20 courses on to it. I have managed to add the courses to display but not in the array plus the way i done it is terrible practice(20 for loops), and on top of that my search bar wont work because the arrays is not being used.
this is my CourseAdapter.java
package com.example.por16002139.lesson41;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class CourseAdapter extends
RecyclerView.Adapter<CourseAdapter.ViewHolder> {
private Context mContext;
private List<Course> mCourseDataset = new ArrayList<>();
private List<Course> mCourseDatasetCopy = new ArrayList<>();
//Search bar filter
// Provide a suitable constructor (depends on the kind of dataset passed in)
public CourseAdapter(Context context, List<Course> CourseDataset) {
mContext = context;
mCourseDataset = CourseDataset;
}
// Create new views (invoked by the LayoutManager)
#NonNull
public CourseAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View itemView =
LayoutInflater.from(parent.getContext()).inflate(R.layout.course_row,
parent, false);
return new CourseAdapter.ViewHolder(itemView);
}
// Replace the contents of the View (invoked by the LayoutManager)
#Override
public void onBindViewHolder(#NonNull CourseAdapter.ViewHolder holder, int
position) {
// Get element from your dataset at this position
// Replace the contents of the View with that element
holder.mCourseImageView.setImageResource(R.drawable.bath_logo);
holder.mCourseNameTextView.setText
(mCourseDataset.get(position).getCourseName());
holder.mCourseTypeTextView.setText
(mCourseDataset.get(position).getCourseType());
}
// Return the size of your dataset (invoked by the LayoutManager)
#Override
public int getItemCount() {
return mCourseDataset.size();
}
public void filter(String text) {
// TODO Filter your EmploymentAdapter here: remember you now have a copy
of all of the Job's that may be helpful that was assigned in the constructor
above!
mCourseDataset.clear();
if(text.isEmpty()){
mCourseDataset.addAll(mCourseDatasetCopy);
} else{
text = text.toLowerCase();
for(Course item: mCourseDatasetCopy){
if(item.getCourseName().toLowerCase().contains(text) ||
item.getCourseType().toLowerCase().contains(text)) {
mCourseDataset.add(item);
}
}
}
notifyDataSetChanged();
}
// Provide a reference to the Views for each data item
// Complex data items may need more than one View per item, and
// you provide access to all the Views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
// each data item is just a string in this case
public ImageView mCourseImageView;
public TextView mCourseNameTextView;
public TextView mCourseTypeTextView;
public ViewHolder(View view) {
super(view);
mCourseImageView = view.findViewById(R.id.course_icon);
mCourseNameTextView = view.findViewById(R.id.coursename);
mCourseTypeTextView = view.findViewById(R.id.coursetype);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, CourseDetailActivity.class);
intent.putExtra("Course_Name",
mCourseDataset.get(getAdapterPosition()).getCourseName());
intent.putExtra("Course_Type",
mCourseDataset.get(getAdapterPosition()).getCourseType());
intent.putExtra("Course_description",
mCourseDataset.get(getAdapterPosition()).getCourseDescription());
mContext.startActivity(intent);
}
}
} }
this is my CourseActivity.java
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class CourseActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private DividerItemDecoration mDividerItemDecoration;
private CourseAdapter mCourseAdapter;
private List<Course> mCourses = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(R.string.course_list);
toolbar.setTitleTextColor(ContextCompat.getColor(getApplicationContext(),
android.R.color.white));
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
if (actionbar != null) {
actionbar.setDisplayHomeAsUpEnabled(true);
}
mRecyclerView = findViewById(R.id.my_recycler_view);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(this); // Construct a new layout manager
for measuring and positioning the RecyclerView
mRecyclerView.setLayoutManager(mLayoutManager);
// Set the RecyclerView.LayoutManager that this RecyclerView will use
mRecyclerView.setHasFixedSize(true);
// RecyclerView to perform several optimisations in advance, as the
RecyclerView's size is not affected by the adapter contents
mRecyclerView.removeItemDecoration(mDividerItemDecoration);
// Remove an RecyclerView.ItemDecoration from this RecyclerView
mDividerItemDecoration = new DividerItemDecoration(this,
DividerItemDecoration.VERTICAL);// Create new DividerItemDecoration
mRecyclerView.addItemDecoration(mDividerItemDecoration);
// Add the DividerItemDecoration to the RecyclerView
for (int i = 0; i < 1; i++) {
Course Course = new Course("Access (Database) – Level 1 CLAIT" + i,
"Part Time Qualification" + i, "Databases are widely used tools in modern
offices today and this course will enable you to learn substantial skills
and provide efficient office support. This course is offered at two levels.
Beginners: you will learn skills varying from table creation, use of
queries, editing and inputting data into new and existing tables. Advanced:
you will learn about formula creation within a query, how to produce reports
and labels and format the design of them once produced." + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("AAT (SAGE) Computerised Accounting Award
Level 2" + i, "Part Time Qualification" + i, "If you already have manual
bookkeeping knowledge, this course is designed to provide you with the basic
skills necessary to input and interrogate information held on computerised
accounting software." + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Animation " + i, "Part Time Love2Learn"
+ i, "This course offers an introductory guide to the animation process from
storyboard to screen, taught by an industry professional. The focus will be
on traditional 2D techniques which will also be applicable to 3D computer-
generated animation. The course is suitable for beginners with an interest
in illustration who want to apply their skills to animation, as well as
those who want to know how animation is produced professionally." + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Asp.Net " + i, "Part Time Love2Learn" +
i, "During this course you will learn how to construct complex websites in a
Microsoft environment using ASP.NET in the C# programming language making
full use of the MVC (model-view-controller) structure." + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Blended Learning, Teaching and
Assessment Technology " + i, "Part Time Love2Learn" + i, "This course is
about learning to make the most of teaching and learning technologies so
that strategic leaders, teachers and TLAs can enrich the traditional
learning environment with 21st century teaching, learning and assessment
tools. Our experience is that busy staff rarely have the the time to keep
pace with rapid changes in technology to independently develop necessary
skills. Schools could use this course to widen the existing learning
environment, to develop staff technical knowledge that will complement
existing pedagogic and curriculum knowledge, and to better prepare learners’
fundamental digital skills. The potential for change includes innovative
teaching and assessment practices, engaging a wider range of learners and
increased learner involvement in tracking and assessment. At the core of
this course are lessons, skills and practices for Assessment For All and
mapping Blooms Taxonomy to the digital learning environment." + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Computers for Work " + i, "Adult
Community Learning" + i, "A 13-hour course (unsuitable for beginners) for
people looking to improve their computer skills for paid employment,
voluntary/charity work, social enterprise or self-employment. You will be
supported by a tutor in small friendly group to: nbrush up and develop your
word processing skills develop the basics of spreadsheets and business
budgeting design and create PowerPoint slides" + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Create Your Own Android App on PC " + i,
"Part Time Love2Learn" + i, "This Android course will teach you the basics
on how to create your own Android app on a PC. Students will be supported
through making their own app that will display pictures from a provided API
before designing and creating an app of their own." + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Digital Art and Design " + i, "Part Time Love2Learn" + i, "Digital technology has become an essential tool for many artists and designers. This course is aimed at supporting artists and designers who wish to incorporate aspects of digital design in their work. Learn about specific programs such as Illustrator and Photoshop (part of Adobe reative Cloud) in our state-of-the-art Mac suites." + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Excel (Spreadsheets) – Level 1 CLAIT " + i, "Part Time Qualification" + i, "Excel spreadsheets are a widely used tool in offices and this course will enable you to learn substantial skills and provide efficient office support. You will cover the basics of inserting and formatting text and numbers within a spreadsheet format and the use of basic formula and chart creation. Attendance is flexible and can be arranged with your tutor on application. This course may also be available at our Somer Valley Campus. Please contact the Student Advice Centre or visit www.bathcollege.ac.uk to register your interest." + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Get Started with iPads " + i, "Adult Community Learning" + i, "Come and have fun and explore touch screen technology with a course designed especially for beginners. Learn how to: navigate the iPad with the swipe screen technique introduction to Applications – “Apps” explore the camera and video functions use and navigate the web feature to surf the internet become familiar with some of the terminology and jargon related to using an iPad" + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Introduction to 3D Games Development in Unity " + i, "Part Time Qualification" + i, "During this course you will learn how to develop a 3D game using the Unity game engine and the C# programming language. The techniques learnt on this course are transferable to all kinds of game development and other types of programming. Throughout this course you will create a simple 3D racing game. Games created using the Unity game engine are compatible with over 10 platforms including Android, iOS, PS4, Xbox One, PC, Mac, Linux and a wide selection of virtual reality headsets." + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Introduction to Linux " + i, "Part Time
Qualification" + i, "Linux powers 94% of the world’s supercomputers, most of
the servers powering the Internet, the majority of financial trades
worldwide and a billion Android devices. During this course you will learn
how to install, maintain and use a Linux system. You will develop a working
knowledge of Linux using both the graphical interface and command line." +
i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Microsoft Excel" + i, "Part Time
Qualification" + i, "This free 5-hour workshop will be run in a small,
friendly, tutor-led group and is suitable for anyone looking to improve
their speadsheet skills – not suitable for beginners. Microsoft Excel is
widely used in all types of businesses and is excellent for organising and
sorting data as well as business planning and performing calculations.
During the workshop you will learn: entering and editing data formatting
cells and worksheets using basic formulas and functions creating, editing
and formatting charts sorting and filtering" + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Microsoft PowerPoint " + i, "Part Time
Qualification" + i, "This free 5-hour workshop will be run in a small,
friendly, tutor led group and is suitable for anyone who would like to
create a PowerPoint presentation – no prior experience of PowerPoint is
required but being able to use the mouse and keyboard is essential. This
workshop will show you how to create a dynamic, informative slideshow using
text, graphics and animation. During the workshop you will learn how to:
create a slide presentation format text and backgrounds insert images create
animations and transitions show a PowerPoint presentation" + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Microsoft Word " + i, "Part Time
Qualification" + i, "Microsoft Word is a popular word processing program
that allows you to create documents such as letters, brochures, CVs, reports
etc. This FREE 5-hour workshop will be run in a small, friendly, tutor-led
group and is suitable for anyone looking to improve their word processing
skills
– not suitable for complete beginners. During the workshop you will learn:
Creating, editing and saving a document Creating folders Formatting text and
paragraphs Cut/copy/paste How to check spelling Inserting images, tables
etc." + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Stay Safe Online " + i, "Part Time
Qualification" + i, "Practical advice and support on how to operate safely
when using internet sites including: looking at parental controls on Windows
PCs and also android and Apple tablets and smart phones how to decide if an
email is dangerous how to restrict use within game sites and on social media
using the internet securely and confidently for the whole family" + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Web Development – An introduction to
HTML " + i, "Part Time Qualification" + i, "This web development course is
an introduction to HTML focusing on the fundamentals of programming web
pages. As well as a gentle introduction we will cover linking pages, file
management, site structure, uploading and downloading web pages, domain
names, browser compatibility and hosting. This course also introduces you to
a range of free applications that enable you to edit pages, upload websites
and create images. This short course is the first stage of a 4-part
programme of study (HTML, CSS, JavaScript & PHP, and MySQL) that can lead
you to developing effective interactive websites and/or mobile web
applications." + i);
mCourses.add(Course);
}
for (int i = 0; i < 1; i++) {
Course Course = new Course("Web Development – Styling with CSS " +
i, "Part Time Qualification" + i, "This web development course enables you
to layout and style your pages using CSS. Learn to style your web content by
thinking in simple building blocks and understanding the ‘box model’, where
you can create mobile-responsive layouts using the flexibility of CSS." +
i);
mCourses.add(Course);
}
// Specify an adapter
mCourseAdapter = new CourseAdapter(this, mCourses);
mRecyclerView.setAdapter(mCourseAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the options menu from XML
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
// SearchView API Reference:
https://developer.android.com/reference/android/widget/SearchView
// Search Overview: https://developer.android.com/guide/topics/search/
// Search Widget:
https://developer.android.com/guide/topics/search/search-
dialog#UsingSearchWidget
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager)
getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView)
menu.findItem(R.id.search_view).getActionView();
// Assumes current activity is the searchable activity
searchView.setSearchableInfo
(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true); // Do not iconify the widget;
expand it by default
searchView.setQueryHint(getString(R.string.search_hint)); // Set query
hint
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
/**
* Called when the user submits the query
* #param query The query text that is to be submitted
* #return False, to let the SearchView perform the default action
*/
#Override
public boolean onQueryTextSubmit(String query) {
// Not really needed in our scenario as we're only concerned
with the filtering of data
return false;
}
/**
* Called when the query text is changed by the user
* #param newText The new content of the query text field
* #return False, indicating the SearchView should perform the
default action of showing any suggestions if available
*/
#Override
public boolean onQueryTextChange(String newText) {
mCourseAdapter.filter(newText); // Filter the items based on the
user search query, searching the title of each traffic event for any partial
matches
mRecyclerView.setAdapter(mCourseAdapter); // Set a new adapter
to provide child views on demand
mCourseAdapter.notifyDataSetChanged(); // Notify any registered
observers that the data set has changed
return false;
}
}); // On query text listener to listen to changes in the user search
query that has been entered
return true;
}
}
this is my Course.java
package com.example.por16002139.lesson41;
public class Course {
private String mCourseName;
private String mCourseType;
private String mCourseDescription;
public Course(String CourseName, String CourseType, String
CourseDescription){
this.mCourseName = CourseName;
this.mCourseType = CourseType;
this.mCourseDescription = CourseDescription;
}
public String getCourseName() {
return mCourseName;
}
public String getCourseType() { return mCourseType; }
public String getCourseDescription() {
return mCourseDescription;
}
}
any ideas? i have googled most of the day, to the point where i am here asking you people for help and i really try not to but i am getting a little desperate, thanks
On https://developer.android.com/reference/android/widget/ArrayAdapter, it says: You can use this adapter to provide views for an AdapterView, Returns a view for each object in a collection of data objects you provide, and can be used with list-based user interface widgets such as ListView or Spinner.
It also says: Note: If you are considering using array adapter with a ListView, consider using RecyclerView instead. RecyclerView offers similar features with better performance and more flexibility than ListView provides. See the Recycler View guide.
You are using RecyclerView.Adapter which is aimed to be used for RecyclerView. Therefore, we are not supposed to use ArrayAdapter with RecyclerView.
I think you can either use ArrayAdapter with ListView instead of RecyclerView or continue to use RecyclerView.Adapter with RecyclerView.
Also, your for loop (int i = 0; i < 1; i++) is redundant because this will loop only once (i = o and that's it). So you just create your 20 Course objects, then mCourses.addAll(Arrays.asList(course1, course2, course3));

Menu option to clear all <EditText>

I am designing an app in Android Studio, but I am having trouble creating a clear option in the menu of my app.
Can someone show me how to add a menu option that will clear all the <EditText> items in my app I am creating?
You can try with below code and change the id of "your_group" with your main layout id.
ViewGroup group = (ViewGroup)findViewById(R.id.your_group);
for (int i = 0, count = group.getChildCount(); i < count; ++i) {
View view = group.getChildAt(i);
if (view instanceof EditText) {
((EditText)view).setText("");//here it will be clear all the EditText field
}
}
Please let me know if have any doubts.

Android instanceof detecting all widgets?

I'm trying to set a font across all TextView's by iterating through the LinearLayout's views and using instanceof.
The form currently consists of 4 TextView's and one Button.
The below code is detecting all Views, even the Button as a TextView?
/* Set fonts */
LinearLayout ll = (LinearLayout) findViewById(R.id.ll_screenincourse_wrapper);
for (int i = 0; i < ll.getChildCount(); i++) {
View v = ll.getChildAt(i);
if (v instanceof TextView) {
((TextView) v).setTypeface(Fonts.get3dDumbFont(this));
}
}
If I log each view's class name it returns the TextView and the Button so I know the correct controls are being picked up.
The problem is the Button and TextView's fonts are being set, and I only want the TextView's.
I have found a work around and that is to do the following but am intrigued as to why the above code does not work as expected.
/* Set fonts */
LinearLayout ll = (LinearLayout) findViewById(R.id.ll_screenincourse_wrapper);
for (int i = 0; i < ll.getChildCount(); i++) {
View v = ll.getChildAt(i);
if (v.getClass().getName().contains("TextView")) {
((TextView) v).setTypeface(Fonts.get3dDumbFont(this));
}
}
Is it because both Button and TextView are of type View? If so, what would be the correct way about doing this?
Any help appreciated, thanks. Ricky.
Actually, Button is a subclass of TextView! That's why you see it as a TextView (it is also a TextView).
http://developer.android.com/reference/android/widget/Button.html
public class Button extends TextView
You could make a second if instanceof to exclude Buttons or use
if (v.getClass() == TextView.class)
But this won't match any other subclasses of TextView (if you use them).
It is simple
Button Class extends TextView Class
Check the documentaion

Checkbox didn't work properly in ListView?

i'm having listview with some items. i placed a Checkbox to display the checkbox with that listitem. I've write onclick method to checkall the checkbox. But, it'll select the item which was in top of the list. What's the problem? Anyone clear me? Thanks in Advance. Sample Code : -
CheckBox c = (CheckBox)findViewById(R.id.checkBox1);
if (c.isChecked())
{
c.setChecked(false);
}
else
{
c.setChecked(true);
}
private OnClickListener checkAllCheckboxes = new OnClickListener(){
public void onClick(View v) {
ListView lv = getListView();
int size = getListAdapter().getCount();
boolean check = lv.isItemChecked(0);
for(int i = 0; i <= size; i++)
lv.setItemChecked(i, !check);
}
}
OR
for(int i=0; i < listView.getChildCount(); i++){
RelativeLayout itemLayout = (RelativeLayout)listView.getChildAt(i);
CheckBox cb = (CheckBox)itemLayout.findViewById(R.id.MyListViewCheckBox);
cb.setChecked(true);
android-unable-to-check-all-the-checkboxes-in-a-custom-listview-because-of-recy
Example2
with that snippet its difficult to point out the issue.
one, the listview reuses the view, maybe that while scrolling the same view is appearing else where.
here is a tutorial http://www.marvinlabs.com/2010/10/custom-listview-ability-check-items/
check it out. or post additional code. particularly, getView in the adapter code.
It happened because at calling of Adapter view it execute at the time of your list view.
So after the you clicked on check box (true) at same number of below screen will be true. for that you have to maintain the Vector.
if(tempVector.get(position)){
holder.box.setChecked(true);
}
else{
holder.box.setChecked(false);
}
try this after your clicking event.

Categories

Resources