I am trying to make a listView that contains only images without texts but it gives a white screen and I am not getting any error or anything.
Here is my codes:
xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="3">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2">
<ListView
android:id="#+id/setOneListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" />
</RelativeLayout>
.........
</LinearLayout>
</LinearLayout>
Activity:
public class Set1_Activity extends Activity {
ListView list;
int[] images = {
R.drawable.iv1, R.drawable.iv2, R.drawable.iv3, R.drawable.iv4,
R.drawable.iv5, R.drawable.iv6, R.drawable.iv11, R.drawable.iv12,
R.drawable.iv13, R.drawable.iv14, R.drawable.iv15, R.drawable.iv16,
R.drawable.iv111, R.drawable.iv112, R.drawable.iv113, R.drawable.iv114,
R.drawable.iv115, R.drawable.iv116, R.drawable.iv7, R.drawable.iv8,
R.drawable.iv9, R.drawable.iv19, R.drawable.iv49, R.drawable.iv50,
R.drawable.iv52, R.drawable.iv54
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main2);
list = (ListView) findViewById(R.id.setOneListView);
HeartlessAdapter adapter = new HeartlessAdapter(this, images);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
switch(position){
case 0:
display.setImageResource(R.drawable.iv1);
tophone = R.drawable.iv1;
break;
.........
class HeartlessAdapter extends ArrayAdapter<String>
{
Context context;
int[] images;
HeartlessAdapter(Context c, int imgs[])
{
super(c, R.layout.imageview);
this.context=c;
this.images=imgs;
}
class MyViewHolder
{
ImageView myImage;
MyViewHolder(View v)
{
myImage = (ImageView) v.findViewById(R.id.imageView);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
MyViewHolder holder = null;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.imageview, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
}
else
{
holder = (MyViewHolder) row.getTag();
}
holder.myImage.setImageResource(images[position]);
return row;
}
}
All works fine, no error and the emulator just show empty white screen nothing inside. What could be missing?
Thanks!
Try moving the android:layout_weight="2" up a level to the horizontal LinearLayout.
1) Let HeartlessAdapter extend ArrayAdapter<Integer> instead of ArrayAdapter<String>.
2) on your constructor, call super(c, R.layout.imageview, imgs); It should work like that.
3) If you wanna optimize it a lot, remove the references to Context and the array of images from the adapter. You can get any item you need calling getItem(position) and the Context by calling getContext().
EDIT:
In order for it to work, call this:
super(c, R.layout.imageview, HeartlessAdapter.toIntegerArray(imgs));
and add this method to HeartlessAdapter:
private static Integer[] toIntegerArray(int[] array){
Integer[] finalArray = new Integer[array.length];
for (int i=0; i<array.length; i++){
finalArray[i] = array[i];
}
return finalArray;
}
try this...
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged()
}
});
Related
The button view shows confirming that the fragment shows, however the recycler view doesn't.
The logged array size of "jobs" is 1, confirming that getItemCount() isn't the problem and that the recycler adapter constructor is called. I'm reusing my JobRecyclerAdapter class but nothing's static, so there shouldn't be any interference between the two instances. The layout is a a copy of a working one I have, minus different ids and layout name, so that shouldn't be a problem either. There are no errors.
Layout
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<include layout="#layout/top_bar"
android:id="#+id/topBarAJ"
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:layout_constraintTop_toTopOf="parent"/>
<include layout="#layout/bottom_bar"
android:id="#+id/bottomBarAJ"
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/activeJobRecyclerView"
app:layout_constraintTop_toBottomOf="#id/topBarAJ"
app:layout_constraintBottom_toTopOf="#id/bottomBarAJ"/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toTopOf="#+id/activeJobRecyclerView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.505"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/topBarAJ" />
</androidx.constraintlayout.widget.ConstraintLayout>
RecyclerAdapter
List<Job> jobs;
List<Drawable> images;
RecyclerViewClickListener clickListener;
public JobRecyclerAdapter(List<Job> downloadedJobs, List<Drawable> images, RecyclerViewClickListener clickListener) {
this.jobs = downloadedJobs;
this.images = images;
Integer arraySize = images.size();
Log.d("downloadActiveJob", "JobRecyclerAdapter: images array size: " + arraySize.toString());
arraySize = jobs.size();
Log.d("downloadActiveJob", "JobRecyclerAdapter: jobs array size: " + arraySize.toString());
this.clickListener = clickListener;
}
class JobCardViewHolder extends RecyclerView.ViewHolder {
public ImageView itemImage;
public TextView itemName;
public TextView itemWeight;
public TextView itemSize;
public TextView transmitterName;
public JobCardViewHolder(View v) {
super(v);//call default constructor
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("RecyclerView", "onClick:" + getAdapterPosition());
clickListener.recyclerViewListClicked(v, getAdapterPosition());
}
});
itemImage = (ImageView) v.findViewById(R.id.itemImage);
itemName = (TextView) v.findViewById(R.id.itemName);
itemWeight = v.findViewById(R.id.itemWeight);
itemSize = v.findViewById(R.id.itemSize);
transmitterName = v.findViewById(R.id.transmitterName);
}
}
public void removeItem(int jobIndex) {
jobs.remove(jobIndex);
notifyDataSetChanged();
}
#Override
public JobCardViewHolder onCreateViewHolder(ViewGroup vg, int n) {
View v = LayoutInflater.from(vg.getContext()).inflate(R.layout.job_card_layout, vg, false);
JobCardViewHolder vH = new JobCardViewHolder(v);
return vH;
}
#Override
public void onBindViewHolder(JobCardViewHolder vH, int position) {
vH.itemName.setText(jobs.get(position).itemName);
vH.itemImage.setImageDrawable(images.get(position));
vH.itemWeight.setText(jobs.get(position).itemWeight);
vH.itemSize.setText(jobs.get(position).itemSize);
vH.transmitterName.setText(jobs.get(position).transmitterName);
}
#Override
public int getItemCount() {
return jobs.size();
}
}
Fragment (I only showed the relevant parts of the fragment.)
RecyclerView jobRecyclerView;
JobRecyclerAdapter jobRecyclerAdapter;
LinearLayoutManager llm;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.sub_fragment_active_jobs_1, container, false);
this.jobRecyclerView = view.findViewById(R.id.activeJobRecyclerView);
return view;
}
public void configureJobsRecyclerAdapter(Job activeJob, List<Drawable> imageDrawables) {
Log.d("downloadActiveJob", "configureJobRecyclerAdapter called");
List<Job> downloadedJobs = new ArrayList<>();
downloadedJobs.add(activeJob);
Integer arraySize = imageDrawables.size();
Log.d("downloadActiveJob", "configureJobRecyclerAdapter: " + arraySize.toString());
jobRecyclerAdapter = new JobRecyclerAdapter(downloadedJobs, imageDrawables, this);
llm = new LinearLayoutManager(context);
jobRecyclerView.setLayoutManager(llm);
jobRecyclerView.setAdapter(jobRecyclerAdapter);
}
Update: If I move the recycler view/adapter setup code to onResume, the recycler view is visible. When I update the recycler view with a new adapter, the recycler view becomes invisible.
If I can't solve it using this new discovery I'll post the whole fragment.
Hey, you create the function configureJobsRecyclerAdapter() but didn't call it inside fragment onCreateView(). Like...
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.sub_fragment_active_jobs_1, container, false);
this.jobRecyclerView = view.findViewById(R.id.activeJobRecyclerView);
configureJobsRecyclerAdapter()//Add this line.
return view;
}
if you are fetching data which are required for configureJobsRecyclerAdapter() from an api maybe you are setting empty list at the time when you are calling configureJobsRecyclerAdapter(). and that's why when you call it in onResume, the list becomes visible(because then data is fetched).
and don't forget to call adapter.notifyDataSetChanged() after each change in your list.
Ok, I have an Listview adapter that contains an ImageView, TextView and another ImageView in that order. So I want to be able to delete the item in list when user presses on second ImageView. When the user press on the item in list it will start TextToSpeech and it will say what is inside TextView. But if the user wants to remove the entry he/she will press on second ImageView which is a delete icon, at that point the item will be remove from the list. Starting the click listener for the imageview is not a problem, the problem is how do I get the number (int) of the corresponding item in listview adapter so I can remove it from array. Here's xml list_item.xml for single entry in list
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp">
<ImageView
android:id="#+id/item_icon_imageview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.15"
android:src="#drawable/ic_record_voice_24dp2"/>
<TextView
android:id="#+id/phrase_textview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.80"
android:textSize="20sp"
android:layout_marginTop="5dp"
android:text="My phone number is 305 666 8454"/>
<ImageView
android:layout_gravity="center"
android:id="#+id/delte_item_imageview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.10"
android:src="#drawable/ic_delete_black_24dp"/>
</LinearLayout>
</RelativeLayout>
The fragment for inflating the listview
public class CustomFragment extends Fragment {
private ArrayAdapter<String> adapter;
private ListView listView;
private FloatingActionButton addPhraseButton;
private TextView phraseTitleTextView;
private TextToSpeech textToSpeech;
private ArrayList<String> phrases;
private static final String PHRASE_LABEL = " Phrases";
private static final String CATEGORY_KEY = "categories";
private ImageView deleteItemImageView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_custom, container, false);
final String categories;
//if we selecte a category sent from home fragment else we got here through menu
Bundle arguments = getArguments();
if (arguments != null && arguments.containsKey(CATEGORY_KEY)) {
categories = arguments.getString(CATEGORY_KEY).toLowerCase();
}
else {
Resources res = view.getResources();
categories = res.getStringArray(R.array.categories)[0].toLowerCase();
}
final Phrases allPhrases = Phrases.getPhrases();
allPhrases.fetchAllPhrases(view.getContext());
phrases = allPhrases.getAllPhrases().get(categories);
phraseTitleTextView = view.findViewById(R.id.label_phrases_txtview);
deleteItemImageView = view.findViewById(R.id.delte_item_imageview);
phraseTitleTextView.setText(categories.substring(0,1).toUpperCase() +
categories.substring(1)+ PHRASE_LABEL);
addPhraseButton = view.findViewById(R.id.add_phrases_btn);
// setting local for text to speech
textToSpeech = new TextToSpeech(getActivity().getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
textToSpeech.setLanguage(Locale.US);
}
});
//setting adapter and listview
adapter = new ArrayAdapter<String>(getContext(), R.layout.entry_item, R.id.phrase_textview, phrases);
listView = (ListView) view.findViewById(R.id.phrases_list);
listView.setAdapter(adapter);
listView.setItemsCanFocus(true);
//activating text to speech when user selects item in listview
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> paren, View view, int position, long id) {
String text = phrases.get(position);
Toast.makeText(getContext(), text, Toast.LENGTH_LONG).show();
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,null, null);
}
});
deleteItemImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
//button to display alert dialog box to add new phrase
addPhraseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addPhraseDialogBox();
}
});
return view;
}
}
You can achieve this through Custom Adapter. Check below:
public class CustomArrayAdapter extends ArrayAdapter<String> {
LayoutInflater inflater;
ArrayList<String> phrases;
public CustomArrayAdapter(Context context, int textViewResourceId, ArrayList<String> items) {
super(context, textViewResourceId, items);
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
phrases = items;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.entry_item, parent, false);
}
....
ImageView deleteItemImageview = (ImageView) convertView.findViewById(R.id. delte_item_imageview);
deleteItemImageview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
phrases.remove(position);
notifyDataSetChanged();
}
});
return convertView;
}
}
I am working on a college project to build an android based mobile learning app. I'm using Parse for backend services. There is a class, namely 'Course' which contains name of the courses to be offered along with an icon for each course. I have written code for custom adapter to display a list of all the courses with icons. The project is executing but the list is not appearing. I cannot figure out what is going wrong.
Here is my SelectCourse.java code
final List<Item> items=new ArrayList<Item>();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Course");
query.orderByAscending("name");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
if (list.size() > 0)
for (int i = 0; i < list.size(); i++) {
final String course = list.get(i).getString("name");
ParseFile image = list.get(i).getParseFile("image");
//adapter.add(course.getString("name"));
image.getDataInBackground(new GetDataCallback() {
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap icon = BitmapFactory.decodeByteArray(
data, 0, data.length);
Item item = new Item(icon, course);
items.add(item);
} else {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
}
} else {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
CustomAdapter adapter=new CustomAdapter(this,items);
ListView listView = (ListView) findViewById(R.id.course_list);
listView.setAdapter(adapter);
This is my CustomAdapter.java code
public class CustomAdapter extends BaseAdapter {
private Context context;
private List<Item> list;
CustomAdapter(Context context, List<Item> list){
this.context = context;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView=convertView;
if(rowView==null) {
ViewHolder viewHolder = new ViewHolder();
LayoutInflater layoutInflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = layoutInflater.inflate(R.layout.list_select_course, parent, false);
viewHolder.icon = (ImageView) rowView.findViewById(R.id.rowImageView);
viewHolder.text = (TextView) rowView.findViewById(R.id.rowTextView);
rowView.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) rowView.getTag();
viewHolder.icon.setImageBitmap(list.get(position).image);
viewHolder.text.setText(list.get(position).text);
return rowView;
}}
Here are ViewHolder and Item
public class ViewHolder {
ImageView icon;
TextView text;}
public class Item {
Bitmap image;
String text;
Item(Bitmap image, String text){
this.image=image;
this.text=text;
}}
This is content_select_course.xml
<LinearLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.rsa.minerva.SelectCourseActivity"
tools:showIn="#layout/app_bar_select_course">
<ListView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/course_list"
android:layout_weight="1" />
And finally list_select_course.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/rowImageView"
android:layout_width="48dp"
android:layout_height="48dp" />
<TextView
android:id="#+id/rowTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/colorButton"
android:text="Hello World"/>
This part of the code:
query.findInBackground(new FindCallback<ParseObject>()
Doesn't run synchronously, meaning that you are actually creating an adapter with no data:
Put this snippet before you call the query.findInBackground():
CustomAdapter adapter=new CustomAdapter(this,items);
ListView listView = (ListView) findViewById(R.id.course_list);
listView.setAdapter(adapter);
And then inside the public void done() callback, put:
adapter.notifyDataSetChanged();
After you add the items to the list with items.add(item).
That should do it.
I am developing an Android application which has a seating plan. The seats are ImageViews placed in the GridView. On click, the imageview will be set to a different image. The problem is no matter which seat I click on, only the first seat's image is changed. Hope to be able to get some help as to why. Following is my code:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
<TextView
android:id="#+id/grid_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="15dp"
android:text="#string/screen"
android:textSize="20sp"
android:gravity="center" >
</TextView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="50dp"
android:paddingRight="50dp"
android:paddingTop="10dp">
<GridView
android:id="#+id/gridView"
android:layout_width="240dp"
android:layout_height="match_parent"
android:paddingTop="15dp"
android:listSelector="#android:color/transparent"
android:numColumns="8"
android:columnWidth="30dp"
android:gravity="center"
android:verticalSpacing="0dp"
android:stretchMode="none"
android:layout_centerInParent ="true">
</GridView>
</RelativeLayout>
</LinearLayout>
seat_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/seatItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity implements OnItemClickListener {
GridView gridview;
ImageAdapter imageAdapter;
ArrayList<Item> data = new ArrayList<Item>();
ImageView image;
boolean showingFirst = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView(); // Initialize the GUI Components
fillData(); // Insert The Data
setDataAdapter(); // Set the Data Adapter
}
// Initialize the GUI Components
private void initView() {
gridview = (GridView) findViewById(R.id.gridView);
gridview.setOnItemClickListener(this);
}
// Insert The Data
private void fillData() {
for (int i = 1; i < 17; i++) {
data.add(new Item(i, getResources().getDrawable(R.drawable.seat)));
}
}
// Set the Data Adapter
private void setDataAdapter() {
imageAdapter = new ImageAdapter(getApplicationContext(),
R.layout.seat_item, data);
gridview.setAdapter(imageAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(final AdapterView<?> arg0, final View view,
final int position, final long id) {
image= (ImageView) findViewById(R.id.seatItem);
if(showingFirst == true){
String message = "Clicked: " + position;
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
.show();
image.setImageResource(R.drawable.seat_blue);
showingFirst = false;
}else{
image.setImageResource(R.drawable.seat);
showingFirst = true;
}
}
}
ImageAdapter.java
public class ImageAdapter extends ArrayAdapter<Item> {
private Context mContext;
int resourceId;
ArrayList<Item> data = new ArrayList<Item>();
ImageView image;
// Constructor
public ImageAdapter(Context c,int layoutResourceId, ArrayList<Item> data) {
super(c, layoutResourceId, data);
this.mContext = c;
this.resourceId = layoutResourceId;
this.data = data;
}
#Override
public Item getItem(int position) {
System.out.println("Get: "+position);
return data.get(position);
}
#Override
public long getItemId(int arg0)
{
return arg0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null)
{
final LayoutInflater layoutInflater =
(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(resourceId, parent, false);
holder = new ViewHolder();
holder.imgItem = (ImageView) convertView.findViewById(R.id.seatItem);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Item item = getItem(position);
System.out.println(position);
holder.imgItem.setImageDrawable(item.getImage());
return convertView;
}
static class ViewHolder
{
ImageView imgItem;
}
}
Use onItemClick second parameter view to access ImageView from ListView clicked row layout:
image= (ImageView)view.findViewById(R.id.seatItem);
At first glance I did not find anything wrong with your code. I would recommend you to try to delegate the click action to the clickable view itself instead of using an onItemClick, so in the getView method use a setonCLickListener to the image view, or the whole view if that is what suits your solution best.
In a side note I would also recommend that you do not use the activity as a callback since in most cases it will lead to an activity leak, create a class or use an anonimous class.
Hope this helps you.
I spent all day searching for an answer, found a lot, but all of them are not what I need.
So, I have a pretty simple menu with ListView and a file for items with TextView. I want to set Segoe-Print font for items in my menu, I know, that I need adapter, but I can't do it. Help!!!
menu.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:id="#+id/menu_top"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/menu_top">
</LinearLayout>
<ListView
android:id="#+id/ListView_Menu"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/fon_android"
android:divider="#drawable/menu_line"
android:textStyle="bold" >
</ListView>
</LinearLayout>
menu_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/menu_prop"
android:layout_width="fill_parent"
android:textSize="19px"
android:text="test string"
android:layout_gravity="left"
android:layout_height="wrap_content"
android:shadowRadius="5"
android:textColor="#color/menu_color"
android:shadowDy="3"
android:shadowDx="3" />
A part of Main_Menu.java:
public class Main_menu extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
ListView menuList = (ListView) findViewById(R.id.ListView_Menu);
String[] items = {
getResources().getString(R.string.system),
getResources().getString(R.string.convert),
getResources().getString(R.string.forks),
getResources().getString(R.string.margin)};
ArrayAdapter<String> adapt = new ArrayAdapter<String>(this,R.layout.menu_item, items);
menuList.setAdapter(adapt);
}
CustomAdapter.java:
public class CustomAdapter extends ArrayAdapter<String> {
public CustomAdapter(Context context, int resource, String[] objects) {
super(context, resource, objects);
// TODO Auto-generated constructor stub
}
public View getView (int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view.findViewById(R.id.menu_prop);
Typeface font = Typeface.createFromAsset(getAssets(), "segoe_print.ttf");
textView.setTypeface(font);
return textView;
}
private AssetManager getAssets() {
// TODO Auto-generated method stub
return null;
}
}
The font doesn't change...
view.txtViewTitle.setTypeface(Typeface.createFromAsset(parent
.getContext().getAssets(), "fonts/DroidSerif.ttf"));
here is code for custom adapter:
private class CostumiseAdapter extends ArrayAdapter<item>{
public CostumiseAdapter(ArrayList<item> items) {
super(getActivity(), 0, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = getActivity().getLayoutInflater().inflate(R.layout.scroll_fragment, null);
}
Item item = getItem(position);
TextView text = (TextView) convertView.findViewById(R.id.text_view);
text.setText(item.mString);
RadioButton b1 = (RadioButton) convertView.findViewById(R.id.radio_b1);
b1.setChecked(item.mB1);
RadioButton b2 = (RadioButton) convertView.findViewById(R.id.radio_b2);
b2.setChecked(item.mB2);
CheckBox cB = (CheckBox) convertView.findViewById(R.id.check_box);
cB.setChecked(item.mB2);
return convertView;
}
}
I've take it from http://androide-examples.blogspot.com/2013/11/android-scroll-list.html see for the full example.
In this example are some semantik mistakes. So you have to fix some items to Items (capitalise)...
You need to create a custom adapter for setting custom font. Here is the minimal code :
public class CustomAdapter extends ArrayAdapter<String> {
//Contructor here
public View getView (int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view.findViewById(R.id.myTextView);
// Here you set the typeface as you do for the TextView
textView.setTypeFace(....);
}
}
That should provide you the custom font for your Listview.
I found a desition!
Well, first of all I create another class for Adapter:
public class Typefaces {
private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
public static Typeface get(Context c, String name) {
synchronized (cache) {
if (!cache.containsKey(name)) {
String path = "fonts/"+name;
try {
Typeface t = Typeface.createFromAsset(c.getAssets(), path);
cache.put(name, t);
} catch (Exception e) {
e.printStackTrace();
}
}
return cache.get(name);
}
}
}
Then in the main Adapter I added two strings:
Typeface tf = Typefaces.get(getContext(), "tahoma.ttf");
holder.txtTitle.setTypeface(tf);
That's all! It's working! )) Thank you all for help and answers.
try in xml:
android:fontFamily="somefont.ttf"
From android 4.1+ the following font are available: http://robotofont.com/
android:fontFamily="sans-serif"
android:fontFamily="sans-serif-thin"
android:fontFamily="sans-serif-light"
android:fontFamily="sans-serif-condensed"
you can also set font programaticly:
TextView t = (TextView) findViewById(R.id.name);
Typeface font = Typeface.createFromAsset(getAssets(),"font/somefont.ttf");
t.setTypeface(font);
put the font file in a folder...