Android GridView Item Order Change when Admob displays - android

I searched for these issues and tried most of the given answers but my issue is not solved yet.
My Grid view has around 10-12 items and and each item has a ImageView and a TextView. image and the texts are dynamically loading from resources.
Issue 1 : When the grid is scrolling the item order changes. first items goes to down and the last items coming to top
Issue 2: When an Admob ad loads in the bottom of the screen entire Grid items are mixing up.Even without any scrolling.
Issue 3: Currently I have put the onClickListeners to the ImageView Only. How do I add the same OnclickListener to the relevant TextView as well
I have used a common gridview generation code found every where in the net.
Here is my code
public class ImageAdapter extends BaseAdapter{
Context myContext;
public ImageAdapter(Context _myContext){
myContext = _myContext;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View MyView = convertView;
try{
if ( convertView == null ){
LayoutInflater li = ((Activity)myContext).getLayoutInflater();
MyView = li.inflate(R.layout.weather_grid, null);
TextView tv = (TextView)MyView.findViewById(R.id.grid_item_text);
Resources res = getResources();
String[] items = res.getStringArray(R.array.weather_items);
final String[] titles = new String[items.length];
int x = 0;
for(String item:items){
titles[x]=item;
x++;
}
// getStringFromRes(titles[position]);
tv.setText(titles[position]);
// Add The Image!!!
final ImageView iv = (ImageView)MyView.findViewById(R.id.grid_item_image);
Class<drawable> resources = R.drawable.class;
Field[] fields = resources.getFields();
String[] imageName = new String[fields.length];
int index = 0;
for( Field field : fields )
{
if(field.getName().startsWith("weather")){
imageName[index] = field.getName();
index++;
}
}
iv.setImageResource(getDrawable(myContext, imageName[position]));
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Clicked Item = " + titles[position]);
Bundle b = new Bundle();
if(titles[position].equals("Weather Overview")){
startActivity(new Intent(WeatherGridActivity.this, WeatherActivity.class));
}
if(titles[position].equals("Current Weather")){
b.putString("display", "current");
Intent intent = new Intent(WeatherGridActivity.this,WeatherActivity.class);
intent.putExtras(b);
startActivityForResult(intent, 0);
//startActivity(new Intent(WeatherGridActivity.this, WeatherActivity.class));
}
if(titles[position].equals("Ask a Question")){
startActivity(new Intent(WeatherGridActivity.this, AskQuestionActivity.class));
}
if(titles[position].equals("Average Temperature")){
startActivity(new Intent(WeatherGridActivity.this, AverageTemperatureActivity.class));
}
}
});
}
}catch(Exception e){
System.out.println("Error Occured = " + e.getMessage());
e.printStackTrace();
}
return MyView;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getCount() {
return 10;
}
public int getDrawable(Context context, String name){
Assert.assertNotNull(context);
Assert.assertNotNull(name);
return context.getResources().getIdentifier(name,"drawable", context.getPackageName());
}
public String getStringFromRes(String name){
try{
int resId = (Integer) R.string.class.getField(name).get(null);
// Toast.makeText(MyContext, getResources().getString(resId), Toast.LENGTH_LONG).show();
return getResources().getString(resId);
}catch(Exception e){
// no such string
return "empty";
}
}
}
Here is the xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg"
android:orientation="vertical" >
<GridView
android:id="#+id/weather"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:columnWidth="70dp"
android:gravity="center_horizontal"
android:horizontalSpacing="20dp"
android:numColumns="auto_fit"
android:padding="20dp"
android:stretchMode="columnWidth"
android:tileMode="repeat"
android:verticalSpacing="20dp" >
</GridView>
<ImageView
android:id="#+id/back_button"
style="#style/book_button" />
<com.google.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="dummy id"
ads:loadAdOnCreate="true"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID" />
</LinearLayout>
</ScrollView>
I have added the RelativeLayout instead of LinerLayout and ScrollViews but now the entire Grid doesn't display but the ads displaying properly.
Here is the new xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="#+id/home_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg"
>
<GridView
android:id="#+id/home_grid"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:columnWidth="100dp"
android:rowHeight="30dp"
android:gravity="center_horizontal"
android:horizontalSpacing="5dp"
android:numColumns="auto_fit"
android:stretchMode="none"
android:tileMode="repeat"
android:verticalSpacing="30dp"
>
</GridView>
<com.google.ads.AdView
android:layout_alignParentBottom="true"
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="dummy id"
ads:loadAdOnCreate="true"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Your answers are highly appreciated
Thanks

Here is the working code. This fix the scrolling issue,the Admob issue and the onClickListener issue as well.
public class ImageAdapter extends BaseAdapter{
Context myContext;
public ImageAdapter(Context _myContext){
myContext = _myContext;
layoutInflater = LayoutInflater.from(myContext);
Resources res = getResources();
String[] items = res.getStringArray(R.array.weather_items);
titles = new String[items.length];
int x = 0;
for(String item:items){
titles[x]=item;
x++;
}
Class<drawable> resources = R.drawable.class;
Field[] fields = resources.getFields();
imageName = new String[fields.length];
int index = 0;
for( Field field : fields ){
if(field.getName().startsWith("weather")){
imageName[index] = field.getName();
index++;
}
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// View MyView = convertView;
View grid = null;
try{
if ( convertView == null ){
grid = new View(myContext);
// LayoutInflater li = ((Activity)myContext).getLayoutInflater();
grid = layoutInflater.inflate(R.layout.weather_grid, null);
}else{
grid = (View)convertView;
}
TextView tv = (TextView)grid.findViewById(R.id.grid_item_text);
tv.setText(titles[position]);
ImageView iv = (ImageView)grid.findViewById(R.id.grid_item_image);
iv.setImageResource(getDrawable(myContext, imageName[position]));
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
executeListners(position);
}
});
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
executeListners(position);
}
});
}catch(Exception e){
System.out.println("Error Occured = " + e.getMessage());
e.printStackTrace();
}
return grid;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getCount() {
return 10;
}
public int getDrawable(Context context, String name){
Assert.assertNotNull(context);
Assert.assertNotNull(name);
return context.getResources().getIdentifier(name,"drawable", context.getPackageName());
}
public String getStringFromRes(String name){
try{
int resId = (Integer) R.string.class.getField(name).get(null);
// Toast.makeText(MyContext, getResources().getString(resId), Toast.LENGTH_LONG).show();
return getResources().getString(resId);
}catch(Exception e){
return "empty";
}
}
}
The xml files has no changes. This works with either RelativeLayout or with a LinearLayout

Related

Get listitem from listview(Customized using Radio Button) when clicked on the Particular Item

I have prepared custom Listview in that i want to select one item from view so for that i have used RadioButton view for single choice item,but i customized it.Following is my total code ,because there may be error in the layout so please help me in solving this.
Activity:-
public class MainActivity extends Activity {
TextView tvEmpty;
ListView listView;
Spinner spnStage;
Button btnGet;
String sfrom;
ArrayList<String> arrayList;
StartFromAdapter arrayAdapter;
String[] stages = { "School", "Collage", "Office" };
String resultdata = "{\"Age\":{\"School\":[{\"Stage\":\"class1\",\"Name\":\"Classname1\"},{\"Stage\":\"class2\",\"Name\":\"ClassName2\"}],\"Collage\":[],\"Office\":[{\"Stage\":\"Office1\",\"Name\":\"Officename1\"},{\"Stage\":\"Office2\",\"Name\":\"Officename2\"}]}}";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvEmpty = (TextView) findViewById(R.id.emptytv);
listView = (ListView) findViewById(R.id.lstDemo);
spnStage = (Spinner) findViewById(R.id.spinner1);
btnGet = (Button) findViewById(R.id.button1);
ArrayAdapter<String> stageAdapter = new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_spinner_item, stages);
stageAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnStage.setAdapter(stageAdapter);
arrayList = new ArrayList<String>();
spnStage.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long id) {
if (arrayList.size() > 0 && arrayList != null) {
arrayList.clear();
}
loadListView(parent.getSelectedItem().toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnGet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = (Integer) v.getTag();
Log.i("SELECTED IN GET", "" + selectedPosition);
}
});
}
public void loadListView(String selectedItem) {
try {
JSONObject jObject = new JSONObject(resultdata);
JSONObject jAge = jObject.getJSONObject("Age");
JSONArray jSelectedItem = jAge.getJSONArray(selectedItem);
if (jSelectedItem.length() != 0) {
for (int i = 0; i < jSelectedItem.length(); i++) {
JSONObject jObj = jSelectedItem.getJSONObject(i);
arrayList.add(jObj.getString("Name"));
}
}
arrayAdapter = new StartFromAdapter(this, arrayList);
arrayAdapter.notifyDataSetChanged();
listView.setAdapter(arrayAdapter);
listView.setEmptyView(tvEmpty);
Log.i("BEFORE LISTVIEW ONCLICK", "THIS IS ADDRESSLIST");
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long id) {
sfrom = ((RadioButton) v.findViewById(R.id.startfromrb))
.getText().toString();
Log.i("STARTFROM", sfrom);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Adapter:-
public class StartFromAdapter extends BaseAdapter {
ArrayList<String> detailsArrayList;
Context context;
int selectedPosition = 0;
public StartFromAdapter(Context context, ArrayList<String> detailsArrayList) {
this.detailsArrayList = detailsArrayList;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return detailsArrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return detailsArrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout rowLayout = null;
if (convertView == null) {
rowLayout = (LinearLayout) LayoutInflater.from(context).inflate(
R.layout.listitem_view, parent, false);
} else {
rowLayout = (LinearLayout) convertView;
}
RadioButton rbStartFrom = (RadioButton) rowLayout
.findViewById(R.id.startfromrb);
rbStartFrom.setChecked(position == selectedPosition);
rbStartFrom.setTag(position);
rbStartFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
notifyDataSetInvalidated();
Log.i("IN ADAPTER", "" + selectedPosition);
}
});
rbStartFrom.setText(detailsArrayList.get(position));
return rowLayout;
}
}
MAINLAYOUT:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_marginBottom="60dp" >
</ListView>
<TextView
android:id="#+id/emptytv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_marginBottom="60dp"
android:gravity="center_vertical|center_horizontal"
android:text="No Records Found."
android:textSize="25sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="31dp"
android:text="Button" />
</RelativeLayout>
listitem_view:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/startfromrb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:focusable="false"
android:focusableInTouchMode="false"
android:lines="3"
android:paddingLeft="20dp"
android:text="RadioButton" />
</LinearLayout>
Update use code as per below
// On item click listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,long itemId) {
RadioButton btn=(RadioButton) view.findViewById(R.id.startfromrb);
String sfrom = btn.getText().toString();
arrayAdapter.setSelected((int)itemId);
Log.i("STARTFROM", sfrom);
}
});
//Add below function in adapter class
public void setSelected(int selectedPosition){
this.selectedPosition=selectedPosition;
notifyDataSetChanged();
}
Also remove from adapter
rbStartFrom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
notifyDataSetInvalidated();
Log.i("IN ADAPTER", "" + selectedPosition);
}
});
And add android:clickable="false" and set selectedPosition to -1 by default
The first I see is, that You have to change the reference to the Views where You want to set the other views below :
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/lstDemo"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1" <!-- correct: #id/spinner1 -->
android:layout_marginBottom="60dp" >
</ListView>
<TextView
android:id="#+id/emptytv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1" <!-- correct: #id/spinner1 -->
android:layout_marginBottom="60dp"
android:gravity="center_vertical|center_horizontal"
android:text="No Records Found."
android:textSize="25sp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="31dp"
android:text="Button" />
</RelativeLayout>
But anyway, Your TextView is sitten directly above the listView, is this Your intention? If not, You have to set
android:layout_below="#+id/lstDemo"
Also, if You get any errors, please post the logcat output. If You just have problems with Your layout, please explain clear enough what exactly You want.
EDIT
try to get the selected item String like this:
final String item = (String) parent.getItemAtPosition(position);
loadListView(item);

Gridview click not working inside the Custom Listview

I'm using gridview inside a Listview, but I have a focusable problem.
I have set the width of the gridview, but I fill some items of gridview, on the left space of gridview (which is blank) means items not fill of gridview in listview. If I click on it, it does not perform a listitem click
As given in the image, I want to perform a listview item click if it is clicked anywhere in the list item. I want to get a listitem click.
But when I click on ListView item, that is, GridView then the ListItem click is not working...
public class History extends Activity {
String name, id, description, count, total;
ArrayList<String> TAG_ID = new ArrayList<String>();
ArrayList<String> TAG_COFFEESHOP_NAME = new ArrayList<String>();
ArrayList<String> TAG_COUNT = new ArrayList<String>();
ArrayList<String> TAG_TOTAL = new ArrayList<String>();
Context context;
JSONArray CoffeeUser = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listlayout);
ListView listView = (ListView) findViewById(R.id.listnew);
listView.setAdapter(new MyCustomAdapter());
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> paramAnonymousAdapterView, View paramAnonymousView, int paramAnonymousInt, long paramAnonymousLong)
{
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView)paramAnonymousView.findViewById(R.id.hlcoffeeshopid)).getText() );
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent);
}
});
}
class MyCustomAdapter extends BaseAdapter {
Context ctx;
public MyCustomAdapter() {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
SharedPreferences prfs = getSharedPreferences("GUID_FILE_NAME", Context.MODE_PRIVATE);
JSONObject json = jParser.methodhistory("http://api.com");
try {
// Getting Array of Employee
CoffeeUser = json.getJSONArray("CoffeeUser");
// Looping of List
for (int i = 0; i < CoffeeUser.length(); i++) {
JSONObject c = CoffeeUser.getJSONObject(i);
// Storing each json item in variable
id = c.getString("CS_Id");
name = c.getString("ShopName");
count = c.getString("totalstamps");
total = c.getString("threshholdcount");
// Adding all get values into array
if (name != "null") {
TAG_COFFEESHOP_NAME.add(name);
TAG_ID.add(id);
TAG_TOTAL.add(total);
TAG_COUNT.add(count);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
return TAG_COFFEESHOP_NAME.size();
}
#Override
public Object getItem(int paramInt) {
return TAG_COFFEESHOP_NAME.get(paramInt);
}
#Override
public long getItemId(int paramInt) {
return paramInt;
}
public class MyCustomHolder {
public GridView localGrid;
public TextView CoffeeShopName,coffeeshopsdescription,coffeeshopid;
}
#Override
public View getView(int paramInt, View paramView,ViewGroup paramViewGroup) {
View localView = paramView;
MyCustomHolder holder = null;
if (localView == null) {
LayoutInflater inflater = (LayoutInflater) History.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
localView = inflater.inflate(R.layout.historylist, null);
holder = new MyCustomHolder();
holder.CoffeeShopName = (TextView) localView.findViewById(R.id.hlcoffeeshopname);
holder.coffeeshopid = (TextView) localView.findViewById(R.id.hlcoffeeshopid);
holder.localGrid = (GridView) localView.findViewById(R.id.gridViewdistorylist);
localView.setTag(holder);
}
else {
holder = (MyCustomHolder) localView.getTag();
}
holder.CoffeeShopName.setText(TAG_COFFEESHOP_NAME.get(paramInt));
holder.coffeeshopid.setText(TAG_ID.get(paramInt));
holder.localGrid.setAdapter(new GridAdapterA(History.this, TAG_TOTAL.get(paramInt), TAG_COUNT.get(paramInt)));
holder.localGrid.setFocusable(false);
holder.localGrid.setFocusableInTouchMode(false);
holder.CoffeeShopName.setFocusable(false);
holder.CoffeeShopName.setFocusableInTouchMode(false);
localView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView)v.findViewById(R.id.hlcoffeeshopid)).getText() );
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent);
}
});
return localView;
}
}
public class GridAdapterA extends BaseAdapter {
private Context context;
String total,count;
public GridAdapterA(Context context) {
this.context = context;
}
public GridAdapterA(Context context, String total, String count) {
// TODO Auto-generated constructor stub
this.context = context;
this.total = total;
this.count = count;
}
public boolean areAllItemsEnabled()
{
return false;
}
public boolean isEnabled(int position)
{
return false;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.customgrid_row, null);
gridView.setFocusable(false);
ImageView imageView = (ImageView) gridView.findViewById(R.id.grid_item_image);
imageView.setFocusable(false);
int i = 0;
if(count!="null")
i = Integer.parseInt(count);
if (position<i ) {
//imageView.setImageResource(R.drawable.ii);
// textView.setText(gridlist[position]);
}
else {
imageView.setImageResource(R.drawable.changedcup);
// textView.setText("");
}
}
else {
gridView = (View) convertView;
}
/*gridView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView)v.findViewById(R.id.hlcoffeeshopid)).getText() );
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent); }
});*/
return gridView;
}
#Override
public int getCount() {
int j=0;
if(total!="null"){
j = Integer.parseInt(total);
}
return j;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
}
historylist
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:orientation="horizontal"
android:padding="5dip" >
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:background="#drawable/image_bg"
android:padding="3dip" >
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip"
android:src="#drawable/rcup" />
</LinearLayout>
<!-- hlcoffeeshopname Of Song -->
<TextView
android:id="#+id/hlcoffeeshopname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="Rihanna Love the way lie"
android:textColor="#040404"
android:textSize="20dip"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/hlcoffeeshopid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
/>
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridViewdistorylist"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#+id/hlcoffeeshopname"
android:layout_toRightOf="#+id/thumbnail"
android:columnWidth="20dp"
android:background="#null"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:focusableInTouchMode="false"
android:numColumns="10"
android:stretchMode="none" >
</GridView>
</RelativeLayout>
New GetView
#Override
public View getView(int paramInt,
View paramView,
ViewGroup paramViewGroup) {
View localView = paramView;
MyCustomHolder holder = null;
if (localView == null) {
LayoutInflater inflater = (LayoutInflater) CopyOfHistory.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
localView = inflater.inflate(R.layout.copyhistorylist, null);
holder = new MyCustomHolder();
holder.coffeeShopName = (TextView) localView.findViewById(R.id.hlcoffeeshopname);
holder.coffeeshopid = (TextView) localView.findViewById(R.id.hlcoffeeshopid);
localView.setTag(holder);
}
else {
holder = (MyCustomHolder) localView.getTag();
}
holder.coffeeShopName.setText(TAG_COFFEESHOP_NAME.get(paramInt));
holder.coffeeshopid.setText(TAG_ID.get(paramInt));
int looplimit = Integer.parseInt(TAG_TOTAL.get(paramInt));
for (int i = 0; i < looplimit; i++) {
Log.e("loop", String.valueOf(looplimit));
ImageView imageView = new ImageView(CopyOfHistory.this);
if (i < Integer.parseInt(TAG_COUNT.get(paramInt))) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.ii));
} else {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.iii));
}
RelativeLayout layout = (RelativeLayout) localView.findViewById(R.id.hlrlayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30,30);
params.setMargins(i*40, 0, 0, 0);
imageView.setLayoutParams(params);
layout.addView(imageView);
//holder.relativeLayout = new RelativeLayout();
}
holder.coffeeShopName.setFocusable(false);
holder.coffeeShopName.setFocusableInTouchMode(false);
localView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView) v
.findViewById(R.id.hlcoffeeshopid)).getText());
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent);
}
});
return localView;
}
You might have solved it, but I have another solution that may help someone.
Use android:descendantFocusability="beforeDescendants" in the root layout of your list_cell XML.
Order to have lists within other lists. You must generate a custom view. If you want one the simple, consisting of a Java class and an XML file, then in the code you only have to instantiate it and add it to a linear layout.
Here I leave a small example.
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical" >
<TextView
android:id="#+id/txtAltaPropinaTextoAyudaTipo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical"
android:text="-"
android:textColor="#000000"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtListadoZonasNombreZona"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_toLeftOf="#+id/txtAltaPropinaTextoAyudaTipo"
android:layout_toRightOf="#+id/txtAltaPropinaTextoAyudaTipo"
android:singleLine="true"
android:text="TextView"
android:textColor="#000000" />
</RelativeLayout>
Java code
public class CVTexto extends RelativeLayout {
public TextView txtTexto;
public int idCv;
public CVTexto(Context context) {
super(context);
// TODO Auto-generated constructor stub
IniciarCuadro();
}
public CVTexto(Context context, AttributeSet attrs) {
super(context, attrs);
IniciarCuadro();
}
public CVTexto(Context context, AttributeSet attrs, int defStyle) {
super( context, attrs, defStyle );
IniciarCuadro();
}
private void IniciarCuadro()
{
//Utilizamos el layout 'control_login' como interfaz del control
String infService = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li =
(LayoutInflater)getContext().getSystemService(infService);
li.inflate(R.layout.ll_adapter_listado_zonas_asignadas_usuario, this, true);
AsignarElemetos();
//Obtenemoslas referencias a los distintos control
//Asociamos los eventos necesarios
// asignarEventos();
}
private void AsignarElemetos(){
txtTexto = (TextView)findViewById(R.id.txtListadoZonasNombreZona);
}
}
Add to linearlayout:
cvTextp objCV = new cvTexto(context);
LinearLayout.addView(objCv);
And delete views:
LinearLayout.removeallViews;
I got this answer by changing the grid layout to LinearLayout. I added items dynamically into linearLayout, and then my problem was solved.
I have done research on it and I get to know that inside a scrollable widget which uses an adapter you should not use any other widget which is scrollable which also uses an adapter such as gridview inside listview because of touch events complexity.
So I think you should move to another approach for this. In your case, you can add a linear layout and can add cup images dynamically into that layout by setting parameters. I hope this helped you.
I don't know how your below code is working, but if I would like handle each on-click listener of each then I would do something like below.
for (int i = 0; i < looplimit; i++) {
Log.e("loop", String.valueOf(looplimit));
ImageView imageView = new ImageView(CopyOfHistory.this);
if (i < Integer.parseInt(TAG_COUNT.get(paramInt))) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.ii));
}
else {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.iii));
}
RelativeLayout layout = (RelativeLayout) localView.findViewById(R.id.hlrlayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30,30);
params.setMargins(i*40, 0, 0, 0);
imageView.setLayoutParams(params);
layout.addView(imageView);
//holder.relativeLayout = new RelativeLayout();
// Handle your each on-click of dynamic added view while they added in getview() method
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what is necessary
}
});
}
I don't know how your below code is working, but if I would like handle each on-click listener of each then I would do something like below.
for (int i = 0; i < looplimit; i++) {
Log.e("loop", String.valueOf(looplimit));
ImageView imageView = new ImageView(CopyOfHistory.this);
if (i < Integer.parseInt(TAG_COUNT.get(paramInt))) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.ii));
}
else {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.iii));
}
RelativeLayout layout = (RelativeLayout) localView.findViewById(R.id.hlrlayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30,30);
params.setMargins(i*40, 0, 0, 0);
imageView.setLayoutParams(params);
layout.addView(imageView);
//holder.relativeLayout = new RelativeLayout();
// Handle your each on-click of dynamic added view while they added in getview() method
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what is necessary
}
});
}

Adapter, convertView, GridView, Images sliding on top, browse outside the gridview

I have some throuble with getting my GridView working as it should.
When I scrol some of the images are sliding much faster than other images (they will not stay in their row). Sometimes I am also able to scrol above the first line! If I skip to use the convertview I have not seen the problem.
---Some additional background---
The imageBufferLoader object below extends a component I am trying to develop. It works as a cash for objects (this time images) with two parameterised windows. One window for maximum objects cashed (to avoid memory problems) and a window for minimum objects loaded (in order to be prepared for scrolling). I have callables that are sent to an executor, one callable for filling the array and one for cleaning the array.
Maybe my problem is thread related.
Here is my adater:
public class WebImageSearchResultAdapter extends BaseAdapter implements
PropertyChangeListener {
private ImageBufferLoader imageBufferLoader;
private Image image = new Image();
private Context context;
private Bitmap bitmapIC_Delete;
private static Handler handleUIEvents;
private LoggerAndroid logger;
private int lastPosRequest;
private RelativeLayout zeroView;
public WebImageSearchResultAdapter(Context context, Parameters parameters) {
this.context = context;
handleUIEvents = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
notifyDataSetChanged();
logger.LogD("Notify Data set Changed");
super.handleMessage(msg);
}
};
bitmapIC_Delete = BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_delete);
logger = new LoggerAndroid(
LoggerAndroid.isLoggingactivewebimagesearchresultadapter(),
"WebImageSearchResultAdapter", "");
Logger loggerImageBuffer = new LoggerAndroid(
LoggerAndroid.isLoggingactiveimagebufferloader(),
"ImageBuffer", "ImageBuffer");
Logger loggerImageDataBuffer = new LoggerAndroid(
LoggerAndroid.isLoggingactiveimagebufferloader(),
"ImageDataBuffer", "ImageDataBuffer");
imageBufferLoader = new ImageBufferLoader(loggerImageBuffer,
loggerImageDataBuffer, parameters, false, 50, 50, false, true, 50, 200);
imageBufferLoader.addChangeListener(this);
try {
imageBufferLoader.startService();
} catch (TimeoutException e) {
ExceptionHandler.getInstance(true).handleException(e);
}
}
public void setParameters(Parameters parameters) {
imageBufferLoader.setParameters(parameters);
zeroView = null;
}
public int getCount() {
// TODO Auto-generated method stub
return 1000;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
logger.LogD("ASK: " + position);
lastPosRequest = position;
RelativeLayout view2 = null;
ImageView imageView = null;
if (convertView == null) {
view2 = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.listimageitem, parent, false);
} else {
view2 = (RelativeLayout) convertView;
}
imageView = (ImageView) view2.findViewById(R.id.imageThumbnail);
if (position == 0 && zeroView != null) {
view2 = zeroView;
} else if (imageBufferLoader.isServiceRunning()
&& imageBufferLoader.isFillCleanRunning()) {
try {
if (imageBufferLoader.isDataAvailable(position)) {
image = imageBufferLoader.getData(position);
imageView.setImageBitmap(image.getThumbnailBitmap());
if(position == 0){
zeroView = view2;
}
logger.LogD("RET IMAGE for: " + position);
} else {
imageView.setImageBitmap(bitmapIC_Delete);
imageBufferLoader.loadData(position);
logger.LogD("RET: IC_DELETE for position " + position +"Request added to Queue");
}
} catch (Exception e) {
ExceptionHandler.getInstance(true).handleException(e);
imageBufferLoader.stopService();
imageView.setImageBitmap(bitmapIC_Delete);
logger.LogD("RET: IC_DELETE for position " + position +" EXCEPTION");
}
} else {
imageView.setImageBitmap(bitmapIC_Delete);
logger.LogD("RET: IC_DELETE for position " + position +" SERVICE NOT RUNNING TRY TO RESTART");
imageBufferLoader.start();
}
return view2;
}
public void propertyChange(PropertyChangeEvent event) {
String proptertyName = event.getPropertyName();
if (proptertyName.equals("Filling Ready")) {
handleUIEvents.sendMessage(new Message());
}
if (proptertyName.equals("BufferCleared")) {
if (imageBufferLoader.isServiceRunning()
&& imageBufferLoader.isFillCleanRunning()) {
imageBufferLoader.loadData(lastPosRequest);
}
}
}
}
Here is my fragment with gridwiev
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<View
android:layout_width="0dp"
android:layout_height="fill_parent" />
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="300dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" >
</GridView>
<View
android:layout_width="0dp"
android:layout_height="fill_parent" />
</LinearLayout>
Here is the layout I inflate in the adapter
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="300dp"
android:layout_height="300dp" >
<ImageView
android:id="#+id/imageThumbnail"
android:layout_width="300dp"
android:layout_height="300dp"
/>
</RelativeLayout>

ListFragment Not Rendering and getView() in Adapter Not Being Called

From what I can gather it appears that this might be because my ListView is not being displayed, I've verified that getCount is returning a value not zero, but I can't see what I'm doing wrong.
Everything loads and acts like it's working but the ListView never appears, I put a background color on the fragment reference in mixed.xml and it is there and taking up the full screen, but when I set a background color on my ListView it does not appear, it's like it's not being rendered at all.
More odd, getView is not being called in my adapter, and this is all working code from regular activities that I ported to fragments.
I've tried calling notifyDataSetChanged which didn't changed anything, debugging shows the adapter is filled with data and getCount is indeed returning an accurate count greater than 0.
Thanks for any help, I'm stuck.
Project is open and can be viewed here http://code.google.com/p/shack-droid/source/browse/#svn%2FTrunk but I'm also including the pertinent code here.
This is the ListFragment:
public class FragmentTopicView extends ListFragment implements ShackGestureEvent {
private ArrayList<ShackPost> posts;
private String storyID = null;
private String errorText = "";
private Integer currentPage = 1;
private Integer storyPages = 1;
private String loadStoryID = null;
private Boolean threadLoaded = true;
private Hashtable<String, String> postCounts = null;
private AdapterLimerifficTopic tva;
public FragmentTopicView() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.topics, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ShackGestureListener listener = Helper.setGestureEnabledContentView(R.layout.topics, getActivity());
if (listener != null) {
listener.addListener(this);
}
if (savedInstanceState == null) {
// get the list of topics
GetChattyAsyncTask chatty = new GetChattyAsyncTask(getActivity());
chatty.execute();
}
ListView lv = getListView();
lv.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// start loading the next page
if (threadLoaded && firstVisibleItem + visibleItemCount >= totalItemCount && currentPage + 1 <= storyPages) {
// get the list of topics
currentPage++;
GetChattyAsyncTask chatty = new GetChattyAsyncTask(getActivity());
chatty.execute();
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
});
}
class GetChattyAsyncTask extends AsyncTask<String, Void, Void> {
protected ProgressDialog dialog;
protected Context c;
public GetChattyAsyncTask(Context context) {
this.c = context;
}
#Override
protected Void doInBackground(String... params) {
threadLoaded = false;
try {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
final String feedURL = prefs.getString("shackFeedURL", getString(R.string.default_api));
final URL url;
if (loadStoryID != null) {
if (currentPage > 1)
url = new URL(feedURL + "/" + loadStoryID + "." + currentPage.toString() + ".xml");
else
url = new URL(feedURL + "/" + loadStoryID + ".xml");
}
else {
if (currentPage > 1)
url = new URL(feedURL + "/" + storyID + "." + currentPage.toString() + ".xml");
else
url = new URL(feedURL + "/index.xml");
}
// Get a SAXParser from the SAXPArserFactory.
final SAXParserFactory spf = SAXParserFactory.newInstance();
final SAXParser sp = spf.newSAXParser();
// Get the XMLReader of the SAXParser we created.
final XMLReader xr = sp.getXMLReader();
// Create a new ContentHandler and apply it to the XML-Reader
SaxHandlerTopicView saxHandler = new SaxHandlerTopicView(c, "topic");
xr.setContentHandler(saxHandler);
// Parse the xml-data from our URL.
xr.parse(new InputSource(HttpHelper.HttpRequestWithGzip(url.toString(), c)));
// Our ExampleHandler now provides the parsed data to us.
if (posts == null) {
posts = saxHandler.GetParsedPosts();
}
else {
ArrayList<ShackPost> newPosts = saxHandler.GetParsedPosts();
newPosts.removeAll(posts);
posts.addAll(posts.size(), newPosts);
}
storyID = saxHandler.getStoryID();
storyPages = saxHandler.getStoryPageCount();
if (storyPages == 0) // XML returns a 0 for stories with only
// one page
storyPages = 1;
}
catch (Exception ex) {
// TODO: implement error handling
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (currentPage == 1)
dialog = ProgressDialog.show(getActivity(), null, "Loading Chatty", true, true);
else
SetLoaderVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ShowData();
SetLoaderVisibility(View.GONE);
try {
dialog.dismiss();
}
catch (Exception e) {
}
}
}
private void ShowData() {
if (posts != null) {
Hashtable<String, String> tempHash = null;
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
final String login = prefs.getString("shackLogin", "");
final int fontSize = Integer.parseInt(prefs.getString("fontSize", "12"));
try {
postCounts = GetPostCache();
}
catch (Exception ex) {
}
if (postCounts != null)
tempHash = new Hashtable<String, String>(postCounts);
if (tva == null) {
tva = new AdapterLimerifficTopic(getActivity(), R.layout.lime_topic_row, posts, login, fontSize, tempHash);
setListAdapter(tva);
}
else {
tva.SetPosts(posts);
tva.notifyDataSetChanged();
}
final ListView lv = getListView();
lv.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Options");
menu.add(0, 1, 0, "Copy Post Url to Clipboard");
menu.add(0, 2, 0, "Watch Thread");
menu.add(0, 3, 0, "Thread Expires In?");
menu.add(0, 4, 0, "Shacker's Chatty Profile");
}
});
// update the reply counts for the listing of topics
try {
UpdatePostCache();
}
catch (Exception e) {
}
}
else {
if (errorText.length() > 0) {
try {
new AlertDialog.Builder(getActivity()).setTitle("Error").setPositiveButton("OK", null).setMessage(errorText).show();
}
catch (Exception ex) {
// could not create a alert for the error for one reason
// or another
Log.e("ShackDroid", "Unable to create error alert ActivityTopicView:468");
}
}
}
threadLoaded = true;
}
}
Here's my FragmentActivity:
public class FragmentActivityTopic extends FragmentActivity {
#Override
protected void onCreate(Bundle arg) {
// TODO Auto-generated method stub
super.onCreate(arg);
setContentView(R.layout.mixed);
}
}
This is the Adapter I'm using, and as mentioned above getView is not being called:
public class AdapterLimerifficTopic extends BaseAdapter {
// private Context context;
private List<ShackPost> topicList;
private final int rowResouceID;
private final String shackLogin;
private final Typeface face;
private final int fontSize;
private final Hashtable<String, String> postCache;
private final String showAuthor;
private final Resources r;
private int totalNewPosts = 0;
LayoutInflater inflate;// = LayoutInflater.from(context);
public AdapterLimerifficTopic(Context context, int rowResouceID, List<ShackPost> topicList, String shackLogin, int fontSize, Hashtable<String, String> postCache) {
this.topicList = topicList;
this.rowResouceID = rowResouceID;
this.shackLogin = shackLogin;
this.fontSize = fontSize;
this.postCache = postCache;
this.r = context.getResources();
face = Typeface.createFromAsset(context.getAssets(), "fonts/arial.ttf");
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
showAuthor = prefs.getString("showAuthor", "count");
inflate = LayoutInflater.from(context);
}
public void SetPosts(List<ShackPost> posts)
{
topicList = posts;
}
#Override
public int getCount() {
return topicList.size();
}
#Override
public Object getItem(int position) {
return topicList.get(position);
}
#Override
public long getItemId(int position) {
// return position;
final ShackPost post = topicList.get(position);
return Long.parseLong(post.getPostID());
}
static class ViewHolder {
TextView posterName;
TextView datePosted;
TextView replyCount;
TextView newPosts;
TextView postText;
TextView viewCat;
RelativeLayout topicRow;
ImageView postTimer;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TextView tmp;
// final View v;
ViewHolder holder;
final ShackPost post = topicList.get(position);
if (convertView == null) {
convertView = inflate.inflate(rowResouceID, parent, false);
holder = new ViewHolder();
holder.posterName = (TextView) convertView.findViewById(R.id.TextViewLimeAuthor);
holder.datePosted = (TextView) convertView.findViewById(R.id.TextViewLimePostDate);
holder.replyCount = (TextView) convertView.findViewById(R.id.TextViewLimePosts);
holder.newPosts = (TextView) convertView.findViewById(R.id.TextViewLimeNewPosts);
holder.postText = (TextView) convertView.findViewById(R.id.TextViewLimePostText);
holder.viewCat = (TextView) convertView.findViewById(R.id.TextViewLimeModTag);
// holder.topicRow = (RelativeLayout) convertView.findViewById(R.id.TopicRow);
// holder.postTimer = (ImageView) convertView.findViewById(R.id.ImageViewTopicTimer);
// holder.posterName.setTypeface(face);
// holder.datePosted.setTypeface(face);
// holder.replyCount.setTypeface(face);
// holder.newPosts.setTypeface(face);
holder.postText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
// holder.postText.setTypeface(face);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
// holder.postTimer.setImageResource(Helper.GetTimeLeftDrawable(post.getPostDate()));
//
holder.posterName.setText(post.getPosterName());
//
// if (shackLogin.equalsIgnoreCase(post.getPosterName()))
// holder.posterName.setTextColor(Color.parseColor("#00BFF3"));
// else
// holder.posterName.setTextColor(Color.parseColor("#ffba00"));
//
holder.datePosted.setText(Helper.FormatShackDateToTimePassed(post.getPostDate()));
holder.replyCount.setText(post.getReplyCount());
//
// if (showAuthor.equalsIgnoreCase("count") && post.getIsAuthorInThread())
// holder.replyCount.setTextColor(Color.parseColor("#0099CC"));
// else
// holder.replyCount.setTextColor(Color.parseColor("#FFFFFF"));
// clipped code
holder.postText.setText(preview);
// if (showAuthor.equalsIgnoreCase("topic") && post.getIsAuthorInThread()) {
// final Drawable d = r.getDrawable(R.drawable.background_gradient_blue);
// holder.topicRow.setBackgroundDrawable(d);
// }
// else
// holder.topicRow.setBackgroundDrawable(null);
// TODO: clean this up a little / also replicated in ShackDroidThread ick
final String postCat = post.getPostCategory();
holder.viewCat.setVisibility(View.VISIBLE);
if (postCat.equals("offtopic")) {
holder.viewCat.setText("offtopic");
holder.viewCat.setBackgroundColor(Color.parseColor("#444444"));
}
else if (postCat.equals("nws")) {
holder.viewCat.setText("nws");
holder.viewCat.setBackgroundColor(Color.parseColor("#CC0000"));
}
else if (postCat.equals("political")) {
holder.viewCat.setText("political");
holder.viewCat.setBackgroundColor(Color.parseColor("#FF8800"));
}
else if (postCat.equals("stupid")) {
holder.viewCat.setText("stupid");
holder.viewCat.setBackgroundColor(Color.parseColor("#669900"));
}
else if (postCat.equals("informative")) {
holder.viewCat.setText("interesting");
holder.viewCat.setBackgroundColor(Color.parseColor("#0099CC"));
}
else
holder.viewCat.setVisibility(View.GONE);
return convertView;
}
public int getTotalNewPosts() {
return totalNewPosts;
}
}
And related XML:
mixed.xml (this is the layout for the fragments, only the one for now)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:id="#+id/LinearLayoutMixed">
<fragment
android:id="#+id/MixedThreads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.stonedonkey.shackdroid.FragmentTopicView"
>
</fragment>
</LinearLayout>
Topics.xml (this contains the ListView as well as a sliding tray and some other stuff.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/TopicLoader"
android:divider="#333333"
android:dividerHeight="1dip"
android:textColor="#FFFFFF"
/>
<RelativeLayout
android:id="#+id/TopicLoader"
android:layout_width="fill_parent"
android:layout_height="35dip"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:visibility="gone"
android:layout_marginTop="5dip" >
<TextView
android:id="#+id/TextViewTopicLoaderText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Loading"
>
</TextView>
<ImageView
android:id="#+id/ImageViewTopicLoader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/TextViewTopicLoaderText"
android:src="#drawable/ic_action_refresh"
android:layout_alignBottom="#+id/TextViewTopicLoaderText"
/>
</RelativeLayout>
<SlidingDrawer
android:id="#+id/SlidingDrawer01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/TopicLoader"
android:animateOnClick="true"
android:content="#+id/bookMarkParent"
android:handle="#+id/TextViewTrayHandle"
android:orientation="vertical"
android:paddingTop="200dip"
android:visibility="gone" >
<TextView
android:id="#+id/TextViewTrayHandle"
android:layout_width="fill_parent"
android:layout_height="35dip"
android:background="#drawable/darkgrey_gradient"
android:focusable="false"
android:focusableInTouchMode="false"
android:gravity="center_vertical" >
</TextView>
<RelativeLayout
android:id="#id/bookMarkParent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/ListViewWatchedThreads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#333333"
android:dividerHeight="1dip"
android:textColor="#FFFFFF" >
</ListView>
</RelativeLayout>
</SlidingDrawer>
</RelativeLayout>
and finally lime_topic_row which is my custom row layout for the ListView in the above layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#FF0000" >
<TextView
android:id="#+id/TextViewLimeModTag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FF0000"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dip"
android:textColor="#000000"
android:padding="2dip"
android:textSize="10dip"
/>
<TextView
android:id="#+id/TextViewLimePostText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="20dip"
android:padding="10dip"
android:layout_below="#+id/TextViewLimeModTag"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/TextViewLimeAuthor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextViewLimePostText"
android:paddingBottom="10dip"
android:paddingLeft="10dip"
android:textColor="#0099CC" />
<TextView
android:id="#+id/TextViewPosted"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextViewLimePostText"
android:layout_toRightOf="#+id/TextViewLimeAuthor"
android:paddingBottom="10dip"
android:text=" posted " />
<TextView
android:id="#+id/TextViewLimePostDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextViewLimePostText"
android:layout_toRightOf="#+id/TextViewPosted"
android:paddingBottom="10dip"
android:paddingRight="10dip"
android:textColor="#FF8800" />
<TextView
android:id="#+id/TextViewLimePosts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/TextViewLimePostDate"
android:layout_marginRight="3dip"
android:layout_below="#+id/TextViewLimePostText"
android:layout_marginBottom="15dip"
android:layout_toLeftOf="#+id/TextViewLimeNewPosts"
android:background="#BBBBBB"
android:padding="3dip"
android:minWidth="25dip"
android:gravity="center"
android:textColor="#000000" />
<TextView
android:id="#+id/TextViewLimeNewPosts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/TextViewLimePostDate"
android:layout_below="#+id/TextViewLimePostText"
android:layout_marginBottom="15dip"
android:layout_marginRight="10dip"
android:background="#669900"
android:padding="3dip"
android:minWidth="25dip"
android:gravity="center"
android:layout_alignParentRight="true"
android:textColor="#000000" />
</RelativeLayout>
I think I found the problem. The issue appears because of the ShackGestureListener that you setup at the start of the onActivityCreated method in the FragmentTopicView:
final ShackGestureListener listener = Helper.setGestureEnabledContentView(R.layout.topics, getActivity());
if (listener != null) {
listener.addListener(this);
}
In the setGestureEnabledContentView() method you check to see if the user enabled the gestures in the preferences or if the android version is bigger then 3. Either way, true or false you set the content view for the FragmentActivityTopic again(with the layout of the FragmentTopicView). Setting the content view again will, unfortunately, cover the current layout which holds the ListView with data(ListView that populates with no problems). When you run those AsyncTasks to get the data, at the end you set the data on the correct ListView(returned by getListView) because the getListView will hold a reference to the old correct ListView which was set in the onCreateView method, but you don't see anything because in the setGestureEnabledContentView you cover this ListView.
This behavior is easy to see if you simple comment out(or remove) the lines that set the content view for the activity in the Helper and HelperAPI4 classes. Another way to see that your ListView is covered is, for example to set the adapter for the ListView(tva) using getListView and using the getActivity().findViewById(android.R.id.list)(I've done this on selecting one of your menus items, so I can control when I replace the adapter):
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId())
{
case R.id.topic_menu_newpost: // Launch post form
//this doesn't work as the getListView will return a reference to the old ListView
ListView lv = getListView();
lv.setAdapter(tva);
// this will work as you get a reference to the new ListView on top
ListView lv = (ListView) getActivity().findViewById(android.R.id.list);
lv.setAdapter(tva);
I don't know what to recommend as a solution as I don't quite understand what you're doing, but I doubt that it requires to set the content view for the activity again(and you should work from this).

ListView with MyAdapter that contains two TextViews and CheckBox

I have a problem syncing the list items isChecked state with the checkboxes that in the same raw. I am able to set the 'checked' state in list items but can't figure how to set the 'checked' state of the CheckBoxes. I thought mainListView.setItemChecked should do the work but it doesn't.
This is the code i'm using:
public class Reservation_Activity extends ListActivity {
int total=0;
private name_price[] lv_arr = {};
private ListView mainListView = null;
final String SETTING_TODOLIST = "todolist";
TextView total_tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reservation);
total_tv = (TextView) findViewById(R.id.total_sum);
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked Save button", Toast.LENGTH_SHORT).show();
}
});
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
total=0;
total_tv.setText("Pick and Send");
Toast.makeText(getApplicationContext(),
" You clicked Clear button", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
// Prepare an ArrayList of todo items
ArrayList<name_price> listTODO = PrepareListFromXml();
this.mainListView = getListView();
mainListView.setCacheColorHint(0);
// Bind the data with the list
lv_arr = (name_price[]) listTODO.toArray(lv_arr);
mainListView.setAdapter(new MyAdapter(this,android.R.layout.simple_list_item_multiple_choice,lv_arr));
mainListView.setItemsCanFocus(false);
mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
name_price item = (name_price) mainListView.getItemAtPosition(position);
if(mainListView.isItemChecked(position))
{
mainListView.setItemChecked(position, false);
total = total - item._price;
} else {
mainListView.setItemChecked(position, true);
total += item._price;
}
total_tv.setText("Total: " + total);
}
});
}
private void ClearSelections() {
total=0;
// user has clicked clear button so uncheck all the items
int count = this.mainListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.mainListView.setItemChecked(i, false);
}
}
private ArrayList<name_price> PrepareListFromXml() {
ArrayList<name_price> todoItems = new ArrayList<name_price>();
XmlResourceParser todolistXml = getResources().getXml(R.xml.order_items);
int id=0;
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = todolistXml.getName();
if (strNode.equals("item")) {
todoItems.add(new name_price(id,todolistXml.getAttributeValue(null, "title"), Integer.parseInt(todolistXml.getAttributeValue(null, "price"))));
id++;
}
}
try {
eventType = todolistXml.next();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return todoItems;
}
public class MyAdapter extends ArrayAdapter<name_price> {
name_price[] items;
public MyAdapter(Context context, int textViewResourceId,
name_price[] objects) {
super(context, textViewResourceId, objects);
this.items = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.list_raw_resevation, parent, false);
TextView name,price;
CheckBox ckbx = (CheckBox) row.findViewById(R.id.UpdateCheckBox);
ckbx.setChecked(mainListView.isItemChecked(position));
name = (TextView) row.findViewById(R.id.res_name);
name.setText(items[position]._name);
price = (TextView) row.findViewById(R.id.res_price);
price.setText(Integer.toString(items[position]._price));
return row;
}
public name_price getItem(int position) {
return items[position];
}
}
}
class name_price {
public String _name;
public int _price;
public int _id;
public CheckBox ckbx;
public name_price(int id, String name, int price)
{
this._id=id;
this._name = name;
this._price = price;
}
public name_price() {
// TODO Auto-generated constructor stub
}
}
I think I should change the checked state of the specific checkbox in mainListView.setOnItemClickListener according to this but I can't find a way to do it.
in addition, This is the raw layout and the list layout (of others to use):
<?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="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<LinearLayout
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="horizontal" >
<TextView
android:id="#+id/res_name"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
android:gravity="center|left"
android:singleLine="true"
android:text="lalalalalalalalalallaallllaaaa"
android:textColor="#ffffff" />
<TextView
android:id="#+id/res_price"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginRight="10dp"
android:gravity="center"
android:text="90"
android:textColor="#ffffff"
android:textSize="15dp" />
</LinearLayout>
<CheckBox android:text=""
android:id="#+id/UpdateCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />
</LinearLayout>
List layout:
<!--?xml version="1.0" encoding="utf-8"?-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#81BEF7"
android:scrollbars="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Buttonlayout" android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:height="32dp" android:gravity="left|top" android:background="#2B60DE"
android:paddingTop="2dp" android:paddingBottom="2dp">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Buttonlayout2" android:orientation="horizontal"
android:layout_height="wrap_content" android:gravity="left|center_vertical"
android:layout_width="wrap_content" android:layout_gravity="left|center_vertical">
<TextView android:id="#+id/total_sum" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:textStyle="bold"
android:textColor="#FFFFFF" android:text="#string/list_header"
android:textSize="15sp" android:gravity="center_vertical"
android:paddingLeft="5dp">
</TextView>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Buttonlayout22" android:orientation="horizontal"
android:layout_height="wrap_content" android:gravity="right"
android:layout_width="fill_parent" android:layout_gravity="right|center_vertical">
<Button android:id="#+id/btnSave" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Send" android:textSize="15sp"
android:layout_marginLeft="10px" android:layout_marginRight="10px"
android:layout_marginBottom="2px" android:layout_marginTop="2px"
android:height="15dp" android:width="70dp">
</Button>
<Button android:id="#+id/btnClear" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Clear" android:textSize="15sp"
android:layout_marginLeft="10px" android:layout_marginRight="10px"
android:layout_marginBottom="2px" android:layout_marginTop="2px"
android:height="15dp" android:width="70dp">
</Button>
</LinearLayout>
</LinearLayout>
<TableLayout android:id="#+id/TableLayout01" android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow>
<ListView android:id="#android:id/list" android:layout_width="wrap_content"
android:textColor="#000000" android:layout_height="wrap_content">
</ListView>
</TableRow>
</TableLayout>
</LinearLayout>
Thanks!
Y
Good morning, I understand this should solve your problem:
public class Reservation_Activity extends ListActivity {
int total = 0;
private name_price[] lv_arr = {};
private ListView mainListView = null;
final String SETTING_TODOLIST = "todolist";
TextView total_tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_raw_resevation);
total_tv = (TextView) findViewById(R.id.total_sum);
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked Save button", Toast.LENGTH_SHORT).show();
}
});
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
total = 0;
total_tv.setText("Pick and Send");
Toast.makeText(getApplicationContext(),
" You clicked Clear button", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
// Prepare an ArrayList of todo items
ArrayList<name_price> listTODO = PrepareListFromXml();
this.mainListView = getListView();
mainListView.setCacheColorHint(0);
// Bind the data with the list
lv_arr = (name_price[]) listTODO.toArray(lv_arr);
mainListView.setAdapter(new MyAdapter(this,
android.R.layout.simple_list_item_multiple_choice, lv_arr));
mainListView.setItemsCanFocus(false);
mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
name_price item = (name_price) mainListView
.getItemAtPosition(position);
if (mainListView.isItemChecked(position)) {
total = total - item._price;
} else {
total += item._price;
}
mainListView.setItemChecked(position,
mainListView.isItemChecked(position));
item.ckbx.setChecked(mainListView.isItemChecked(position));
total_tv.setText("Total: " + total);
}
});
}
private void ClearSelections() {
total = 0;
int count = this.mainListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.mainListView.setItemChecked(i, false);
}
}
private ArrayList<name_price> PrepareListFromXml() {
ArrayList<name_price> todoItems = new ArrayList<name_price>();
XmlResourceParser todolistXml = getResources().getXml(R.xml.order_items);
int id = 0;
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = todolistXml.getName();
if (strNode.equals("item")) {
todoItems.add(new name_price(id, todolistXml.getAttributeValue(null, "title"),Integer.parseInt(todolistXml.getAttributeValue(null,"price"))));
id++;
}
}
try {
eventType = todolistXml.next();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return todoItems;
}
public class MyAdapter extends ArrayAdapter<name_price> {
name_price[] items;
View row;
CheckBox ckbx;
public MyAdapter(Context context, int textViewResourceId,name_price[] objects) {
super(context, textViewResourceId, objects);
this.items = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.reservation, parent, false);
TextView name, price;
ckbx = (CheckBox) row.findViewById(R.id.UpdateCheckBox);
ckbx.setChecked(mainListView.isItemChecked(position));
ckbx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name_price item = (name_price) mainListView.getItemAtPosition(position);
if (ckbx.isChecked()) {
total = total - item._price;
} else {
total += item._price;
}
mainListView.setItemChecked(position,ckbx.isChecked());
total_tv.setText("Total: " + total);
}
});
items[position].setCkbx(ckbx);
name = (TextView) row.findViewById(R.id.res_name);
name.setText(items[position]._name);
price = (TextView) row.findViewById(R.id.res_price);
price.setText(Integer.toString(items[position]._price));
return row;
}
public name_price getItem(int position) {
return items[position];
}
}
}
and:
class name_price {
public String _name;
public int _price;
public int _id;
public CheckBox ckbx;
public name_price(int id, String name, int price) {
this._id = id;
this._name = name;
this._price = price;
}
public void setCkbx(CheckBox ckbx) {
this.ckbx = ckbx;
}
}

Categories

Resources