I want the list view and tab bar both at the same time and my code is below:
Please check my Main Activity and Custom Adapter and tell me what changes I need to do.
Because list is working but tabs are not being displayed.
Two XML files I have included.
1.tab_bar
2.final_tab_item
Please let me know where I am going wrong...
MainActivity.java
package com.example.tabwithlist;
import java.util.ArrayList;
import com.example.customlist.CustomAdapter;
import com.example.customlist.ListModel;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
public class MainActivity extends TabActivity implements OnTabChangeListener
{
ListView list;
CustomAdapter adapter;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
/** Called when the activity is first created. */
TabHost tabHost;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_bar);
// setContentView(R.layout.custom_list_view);
setListData();
Resources res =getResources();
list=(ListView)findViewById(R.id.listnew);
//**************** Create Custom Adapter *********//*
adapter=new CustomAdapter(this, CustomListViewValuesArr,res);
list.setAdapter(adapter);
for (int i = 0; i < 11; i++) {
final ListModel sched = new ListModel();
//******* Firstly take data in model object ******//*
sched.setCompanyName("Company "+i);
sched.setImage("image"+i);
sched.setUrl("http:\\\\www."+i+".com");
//******** Take Model Object in ArrayList **********//*
CustomListViewValuesArr.add(sched);
}
// Get TabHost Refference
tabHost = getTabHost();
// Set TabChangeListener called when tab changed
tabHost.setOnTabChangedListener(this);
TabHost.TabSpec spec;
Intent intent;
//************* TAB1 ************//*
// Create Intents to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, Tab1.class);
spec = tabHost.newTabSpec("First").setIndicator("")
.setContent(intent);
//Add intent to tab
tabHost.addTab(spec);
//************* TAB2 ************//*
intent = new Intent().setClass(this, Tab2.class);
spec = tabHost.newTabSpec("Second").setIndicator("")
.setContent(intent);
tabHost.addTab(spec);
/************* TAB3 ************/
intent = new Intent().setClass(this, Tab3.class);
spec = tabHost.newTabSpec("Third").setIndicator("")
.setContent(intent);
tabHost.addTab(spec);
// Set drawable images to tab
tabHost.getTabWidget().getChildAt(1).setBackgroundResource(R.drawable.tab2);
tabHost.getTabWidget().getChildAt(2).setBackgroundResource(R.drawable.tab3);
// Set Tab1 as Default tab and change image
tabHost.getTabWidget().setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).setBackgroundResource(R.drawable.tab1_over);
}
private void setListData() {
for (int i = 0; i < 11; i++) {
final ListModel sched = new ListModel();
/******* Firstly take data in model object ******/
sched.setCompanyName("Company "+i);
sched.setImage("image"+i);
sched.setUrl("http:\\\\www."+i+".com");
/******** Take Model Object in ArrayList **********/
CustomListViewValuesArr.add(sched);
}
}
#Override
public void onTabChanged(String tabId) {
/************ Called when tab changed *************/
//********* Check current selected tab and change according images *******/
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
if(i==0)
tabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.tab1);
else if(i==1)
tabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.tab2);
else if(i==2)
tabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.tab3);
}
Log.i("tabs", "CurrentTab: "+tabHost.getCurrentTab());
if(tabHost.getCurrentTab()==0)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundResource(R.drawable.tab1_over);
else if(tabHost.getCurrentTab()==1)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundResource(R.drawable.tab2_over);
else if(tabHost.getCurrentTab()==2)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundResource(R.drawable.tab3_over);
}
}
CustomAdapter.java(Here I am inflating my final_tab_item.xml file which displays how list view will look like.)
package com.example.customlist;
import java.util.ArrayList;
import android.R;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
//import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter {
/*********** Declare Used Variables *********/
private Activity activity;
private ArrayList data;
private static LayoutInflater inflater=null;
public Resources res;
ListModel tempValues=null;
int i=0;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Activity a, ArrayList d,Resources resLocal) {
/********** Take passed values **********/
activity = a;
data=d;
res = resLocal;
/*********** Layout inflator to call external xml layout () **********************/
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(data.size()<=0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder to contain inflated xml file elements ***********/
public static class ViewHolder{
public TextView text;
public TextView text1;
public TextView textWide;
public ImageView image;
}
/*********** Depends upon data size called for each row , Create each ListView row ***********/
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/********** Inflate tabitem.xml file for each row ( Defined below ) ************/
//vi = inflater.inflate(R.layout., null);
vi=inflater.inflate(com.example.tabwithlist.R.layout.final_tab_item,null);
/******** View Holder Object to contain tabitem.xml file elements ************/
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(com.example.tabwithlist.R.id.text);
holder.text1=(TextView)vi.findViewById(com.example.tabwithlist.R.id.text1);
holder.image=(ImageView)vi.findViewById(com.example.tabwithlist.R.id.image);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
if(data.size()<=0)
{
holder.text.setText("No Data");
}
else
{
/***** Get each Model object from Arraylist ********/
tempValues=null;
tempValues = (ListModel) data.get(position);
/************ Set Model values in Holder elements ***********/
holder.text.setText(tempValues.getCompanyName());
holder.text1.setText(tempValues.getUrl());
holder.image.setImageResource(res.getIdentifier("com.example.tabwithlist:drawable/"+tempValues.getImage(),null,null));
/******** Set Item Click Listner for LayoutInflater for each row ***********/
// vi.setOnClickListener(new OnItemClickListener(position));
}
return vi;
}
}
tab_bar.xml(In this file I am declaring list view and tab bar)
<?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">
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</RelativeLayout>
</TabHost>
<ListView
android:id="#+id/listnew"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
Ur MainActivity loads the tabs only, put our listview code in first tab (Tab1.class)
Changes:
tab_bar.xml with
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</RelativeLayout>
</TabHost>
remove all the listview code from ur MainActivity.
Create Tab1, Tab2 and Tab3 activities.
Create new xml add
<ListView
android:id="#+id/listnew"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
Move all the listview code to Tab1.java
Related
Radio Buttons Deselected on scrolling in custom listview
i have made custom listview that add
run time radiobutton added autimatically
but it deselected on scroll
my code given below of adapter and mainclass and activity files
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#drawable/gradient11"
android:layout_width="match_parent" android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="option one is selected now so you can"
android:textColor="#00ff00"
android:id="#+id/op1"/>
<RadioButton
android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="op2"
android:textColor="#00ff00"
android:id="#+id/op2"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="op3"
android:textColor="#00ff00"
android:id="#+id/op3"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="op4"
android:textColor="#00ff00"
android:id="#+id/op4"/>
</RadioGroup>
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/quest"
android:textColor="#e2000000"/>
</LinearLayout>
The Adapter file
package com.patel.ravin.com.domparsing;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by lenovo on 08-08-2016.
*/
public class Adpt extends BaseAdapter
{
Context context;
ArrayList<MyBean> arrayList;
public Adpt(Context context,ArrayList<MyBean> arrayList)
{
this.context=context;
this.arrayList=arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.listview, null);
TextView txtFName = (TextView) view.findViewById(R.id.qid);
TextView txtLName = (TextView) view.findViewById(R.id.quest);
RadioButton op1=(RadioButton)view.findViewById(R.id.op1);
RadioButton op2=(RadioButton)view.findViewById(R.id.op2);
RadioButton op3=(RadioButton)view.findViewById(R.id.op3);
RadioButton op4=(RadioButton)view.findViewById(R.id.op4);
MyBean myBean = arrayList.get(i);
txtFName.setText("" + myBean.getQid());
txtLName.setText(" Answer= " + myBean.getQname());
op1.setText(myBean.getOp1());
op2.setText(myBean.getOp2());
op3.setText(myBean.getOp3());
op4.setText(myBean.getOp4());
return view;
}
}
The Activity file
package com.patel.ravin.com.domparsing;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.patel.ravin.com.domparsing.AsyncTask.AsyncTaskLoader;
import com.patel.ravin.com.domparsing.AsyncTask.OnAsyncResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
TextView textView;
ListView listView1;
Adpt adpt;
ArrayList<MyBean> arrayList=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// textView= (TextView) findViewById(R.id.tv1);
listView1=(ListView)findViewById(R.id.llv);
// Adpt adpt=new Adpt(getApplicationContext(),arrayList);
//listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,arrayList));
OnAsyncResult onAsyncResult=new OnAsyncResult() {
#Override
public void onAsyncResult(String result) {
Log.e("h", result.toString());
try {
// textView.setText(""+result.toString());
// String co=result.toString();
JSONArray jsonArray=new JSONArray(result);
MyBean myBean;
arrayList = new ArrayList<>();
for(int i=1;i<=jsonArray.length();i++)
{
JSONObject jsonObject=jsonArray.getJSONObject(i);
myBean = new MyBean();
myBean.setQid(jsonObject.getString("que"));
myBean.setQname(jsonObject.getString("ans"));
myBean.setOp1(jsonObject.getString("a"));
myBean.setOp2(jsonObject.getString("b"));
myBean.setOp3(jsonObject.getString("c"));
myBean.setOp4(jsonObject.getString("d"));
arrayList.add(myBean);
listView1.setAdapter(new Adpt(getApplicationContext(),arrayList));
}
//JSONObject object = new JSONObject(result);
//String contact = object.getString("que");
// textView.setText(co);
} catch (Exception e) {
e.printStackTrace();
}
}
};
AsyncTaskLoader asyncTaskLoader=new AsyncTaskLoader(MainActivity.this,onAsyncResult,null,"http://quiz/jsonapi.php");
asyncTaskLoader.execute();
}
}
Radio Buttons Deselected on scrolling in custom listview
i have made custom listview that add
run time radiobutton added autimatically
but it deselected on scroll
This is a very common problem in Android with Listviews and Radio buttons.
First, I would recommend you to check this post:
Using radio button in custom listview in Android
Now, I'm going to tell you which solution fits for me. In my case I use GridView, but it also works for ListView.
In your Adapter's class you have to have a variable for the selected item and his index, it could be something like:
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
Then, define a function to retrieve this information:
public int getItemSelected(){
return mSelectedPosition;
}
Now, In order to make it works properly, you have to user a ViewHolder (in my case every item in the GridView has a Image and a RadioButton), so you define your ViewHolder in the Adapter's class as well:
private class ViewHolder {
ImageView image;
RadioButton radio;
}
Then, in your getView function, you have to work with the ViewHolder. In the code I write comments to follow.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView; // assign the view
ViewHolder holder; // declare the ViewHolder
if(view == null){
// cutom layout for each row (item) of the ListView
view = mLayoutInflater.inflate(R.layout.item_list_company, parent, false);
holder = new ViewHolder();
// initialize the ViewHolder's field
holder.image = (ImageView) view.findViewById(R.id.c1);
holder.radio = (RadioButton)view.findViewById(R.id.cN1);
view.setTag(holder); // set the tag
}else{ // already initialized
holder = (ViewHolder)view.getTag(); // so we only set the tag
}
// on click triggered for each RadioButton in the ListView
holder.radio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position != mSelectedPosition && mSelectedRB != null){
mSelectedRB.setChecked(false); // uncheck the last one
}
mSelectedPosition = position; // change the item selected index
mSelectedRB = (RadioButton)v; // assign the new item selected
}
});
// just to control the right item checked
if(mSelectedPosition != position){
holder.radio.setChecked(false);
}else{
holder.radio.setChecked(true);
if(mSelectedRB != null && holder.radio != mSelectedRB){
mSelectedRB = holder.radio;
}
}
return view;
}
Finally, in the custom layout (item_list_company.xml in my case) for each item in the ListView, I have the following code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<ImageView android:id="#+id/c1"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="centerInside" />
<RadioButton
android:id="#+id/cN1"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:buttonTint="#color/colorPrimary"
android:textColor="#color/colorAccent"
android:focusable="false"
android:layout_gravity="left"
android:clickable="false"
android:focusableInTouchMode="false"
android:textSize="20dp"/>
</LinearLayout>
Special attention for this three attributes of the RadioButton:
android:focusable="false"
android:clickable="false"
android:focusableInTouchMode="false"
So, with all of this, you only have to set your adapter and ListView in your Activity and call to the right function to retrieve the selected item:
ArrayList<MyBean> arrayList = new ArrayList<>();
ListView listView1 = (ListView)findViewById(R.id.llv);
Adpt adpt = new Adpt(getApplicationContext(), arrayList);
// add data to the ArrayList
adpt.notifyDataSetChanged(); // notify for the new data in the ArrayList
// retrieve the item selected
int selected = adpt.getItemSelected();
Hope it helps!
I want to create a ListView in a Fragment for chats just like WhatsApp but the adapter is showing null. Below is my code :
ChatsFragment.java
package com.houssup.userchat;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
public class ChatsFragment extends Fragment {
ListView list;
CustomChatAdapter adapter;
public ChatsFragment chatsFragment = null;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.customrow_chat, container, false);
ListView lv= ( ListView )view.findViewById( R.id.list ); // List defined in XML ( See Below )
/**************** Create Custom Adapter *********/
setListData();
adapter=new CustomChatAdapter( getContext(), CustomListViewValuesArr);
lv.setAdapter(adapter);
return view;
}
public void setListData()
{
for (int i = 0; i < 11; i++) {
final ListModel sched = new ListModel();
/******* Firstly take data in model object ******/
sched.setName("Swapnil"+i);
sched.setDesignation("Interior Designer"+i);
/******** Take Model Object in ArrayList **********/
CustomListViewValuesArr.add( sched );
}
}
}
CustomChatAdapter.java
package com.houssup.userchat;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.res.Resources;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Created by hp on 01-06-2016.
*/
public class CustomChatAdapter extends BaseAdapter{
private Context context;
private ArrayList data;
private static LayoutInflater inflater=null;
ListModel tempValues=null;
int i=0;
/************* CustomChatAdapter Constructor *****************/
public CustomChatAdapter(Context context, ArrayList d) {
/********** Take passed values **********/
this.context=context;
data=d;
/*********** Layout inflator to call external xml layout () ***********/
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(data.size()<=0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder{
public TextView name;
public TextView designation;
public CircleImageView image;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.customrow_chat, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.name = (TextView) vi.findViewById(R.id.name);
holder.designation=(TextView)vi.findViewById(R.id.designation);
holder.image= (CircleImageView) vi.findViewById(R.id.image);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
if(data.size()<=0)
{
holder.name.setText("No Data");
}
else
{
/***** Get each Model object from Arraylist ********/
tempValues=null;
tempValues = ( ListModel ) data.get( position );
/************ Set Model values in Holder elements ***********/
holder.name.setText( tempValues.getName() );
holder.designation.setText( tempValues.getDesignation() );
holder.image.setImageResource(R.drawable.circuladp);
/******** Set Item Click Listner for LayoutInflater for each row *******/
/* vi.setOnClickListener(new OnItemClickListener( position ));*/
}
return vi;
}
/* #Override
public void onClick(View v) {
Log.v("CustomChatAdapter", "=====Row button clicked=====");
}*/
/********* Called when Item click in ListView ************/
/* private class OnItemClickListener implements View.OnClickListener {
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
*//*#Override
public void onClick(View arg0) {
CustomListViewAndroidExample sct = (CustomListViewAndroidExample)activity;
*//**//**** Call onItemClick Method inside CustomListViewAndroidExample Class ( See Below )****//**//*
sct.onItemClick(mPosition);
}*/
}
fragment_chats.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.houssup.userchat.ChatsFragment">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</FrameLayout>
customrow_chat.xml
<?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="wrap_content"
android:orientation="horizontal">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profile_image"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/circuladp"
app:civ_border_width="2dp"
app:civ_border_color="#FF000000"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_below="#id/title"
android:text="Yashvant Rai Bacchhan"
android:layout_marginLeft="50dp"
android:textSize="18dp"
android:textColor="#000000"
android:layout_marginTop="10dp"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/designation"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="6dp"
android:layout_marginLeft="55dp"
android:textSize="14dp"
android:layout_height="wrap_content"
android:text="Designer"/>
</LinearLayout>
</LinearLayout>
This fragment is in a TabActivity.I don't know why it is showing null. Any help will be appreciated !!
The code shows that you inflating the fragment view for the layout 'R.layout.customrow_chat' but the layout name is 'fragment_chats.xml'. Typo?
See you code. you convertView is always null.
change it:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
convertView = inflater.inflate(R.layout.customrow_chat, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.designation=(TextView)convertView.findViewById(R.id.designation);
holder.image= (CircleImageView) convertView.findViewById(R.id.image);
/************ Set holder with LayoutInflater ************/
convertView.setTag( holder );
}
else
holder=(ViewHolder)convertView.getTag();
if(data.size()<=0)
{
holder.name.setText("No Data");
}
else
{
/***** Get each Model object from Arraylist ********/
tempValues=null;
tempValues = ( ListModel ) data.get( position );
/************ Set Model values in Holder elements ***********/
holder.name.setText( tempValues.getName() );
holder.designation.setText( tempValues.getDesignation() );
holder.image.setImageResource(R.drawable.circuladp);
/******** Set Item Click Listner for LayoutInflater for each row *******/
/* vi.setOnClickListener(new OnItemClickListener( position ));*/
}
return convertView;
}
i have a application with slidemenu that have some fragments in it
two custom adapter i used that both of them are same code and just one of them have a image more than another
customadapter file is:
package ir.monocode.az;
import ir.monocode.az.R;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/********* Adapter class extends with BaseAdapter and implements with OnClickListener ************/
public class CustomAdapter extends BaseAdapter implements OnClickListener {
/*********** Declare Used Variables *********/
private Context activity;
private ArrayList data;
private static LayoutInflater inflater=null;
public Resources res;
CatsModel tempValues=null;
int i=0;
Context context;
Typeface face;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Context context, ArrayList d,Resources resLocal) {
/********** Take passed values **********/
activity = context;
data=d;
res = resLocal;
/*********** Layout inflator to call external xml layout () **********************/
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(data.size()<=0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder to contain inflated xml file elements ***********/
public static class ViewHolder{
public TextView text;
public ImageView image;
}
/*********** Depends upon data size called for each row , Create each ListView row ***********/
public View getView(int position, View convertView, ViewGroup parent) {
View vii=convertView;
ViewHolder holder;
if(convertView==null){
/********** Inflate tabitem.xml file for each row ( Defined below ) ************/
vii = inflater.inflate(R.layout.catitems, null);
/******** View Holder Object to contain tabitem.xml file elements ************/
holder=new ViewHolder();
holder.text=(TextView)vii.findViewById(R.id.ctextView1);
holder.image=(ImageView)vii.findViewById(R.id.cimageView2);
Typeface typeface = Typeface.createFromAsset(holder.text.getContext().getAssets(),
"fonts/B YEKAN.TTF");
holder.text.setTypeface(typeface);
/************ Set holder with LayoutInflater ************/
vii.setTag(holder);
}
else
holder=(ViewHolder)vii.getTag();
if(data.size()<=0)
{
holder.text.setText("No Data");
}
else
{
/***** Get each Model object from Arraylist ********/
tempValues=null;
tempValues = (CatsModel) data.get(position);
/************ Set Model values in Holder elements ***********/
holder.text.setText(tempValues.getCatName());
int resID = activity.getResources().getIdentifier("icon"+tempValues.getImage() , "drawable", activity.getPackageName());
holder.image.setImageResource(resID);
/******** Set Item Click Listener for LayoutInflater for each row ***********/
vii.setOnClickListener(new OnItemClickListener(position));
}
return vii;
}
#Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
MainActivity sct = (MainActivity)activity;
sct.customonItemClick(mPosition);
}
}
}
articleadapter is:
package ir.monocode.az;
import ir.monocode.azmoonEstekhdami.R;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
/********* Adapter class extends with BaseAdapter and implements with OnClickListener ************/
public class ArticleAdapter extends BaseAdapter implements OnClickListener {
/*********** Declare Used Variables *********/
private Context activity;
private ArrayList data;
private static LayoutInflater inflater=null;
public Resources res;
ArticlesModel tempValues=null;
int i=0;
Context context;
Typeface face;
/************* CustomAdapter Constructor *****************/
public ArticleAdapter(Context context, ArrayList d,Resources resLocal) {
/********** Take passed values **********/
activity = context;
data=d;
res = resLocal;
/*********** Layout inflator to call external xml layout () **********************/
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(data.size()<=0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder to contain inflated xml file elements ***********/
public static class ViewHolder{
public TextView text;
}
/*********** Depends upon data size called for each row , Create each ListView row ***********/
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/********** Inflate tabitem.xml file for each row ( Defined below ) ************/
vi = inflater.inflate(R.layout.articleitems, null);
/******** View Holder Object to contain tabitem.xml file elements ************/
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.atextView1);
Typeface typeface = Typeface.createFromAsset(holder.text.getContext().getAssets(),
"fonts/B YEKAN.TTF");
holder.text.setTypeface(typeface);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
if(data.size()<=0)
{
holder.text.setText("No Data");
}
else
{
/***** Get each Model object from Arraylist ********/
tempValues=null;
tempValues = (ArticlesModel) data.get(position);
/************ Set Model values in Holder elements ***********/
holder.text.setText(tempValues.getArticleName());
}
return vi;
}
#Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
MainActivity sct = (MainActivity)activity;
sct.articleItemClick(mPosition);
}
}
}
and of course i have two xml layout for my items style:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cLinearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:gravity="right"
android:orientation="vertical"
android:paddingBottom="10dp" >
<LinearLayout
android:id="#+id/cLinearLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:gravity="right" >
<TextView
android:id="#+id/ctextView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:paddingRight="10dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#215e76"
android:textSize="20sp" />
<ImageView
android:id="#+id/cimageView2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:maxHeight="20dp"
android:maxWidth="20dp"
android:padding="5dp"
android:src="#drawable/ic_launcher" />
<ImageView
android:id="#+id/cimageView1"
android:layout_width="10dp"
android:layout_height="match_parent"
android:background="#ffc20e" />
</LinearLayout>
</LinearLayout>
and another is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/aLinearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:gravity="right"
android:orientation="vertical"
android:paddingBottom="10dp" >
<LinearLayout
android:id="#+id/aLinearLayout3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:gravity="right" >
<TextView
android:id="#+id/atextView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:paddingRight="10dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#215e76"
android:textSize="20sp" />
<ImageView
android:id="#+id/aimageView1"
android:layout_width="10dp"
android:layout_height="match_parent"
android:background="#ffc20e" />
</LinearLayout>
</LinearLayout>
now when i run program
fragment that fill with customadapter work very good
but fragment that filled by articlesadapter have below error
java.lang.ClassCastException: ir.monocode.az.ArticlesModel cannot be cast to ir.monocode.az.CatsModel
how i must solve my problem?
can you help me please?
thank you
You can solve with polymorphism. Replace the failing declaration (the one your cast error comes from) with the Interface BaseAdapter
Something like this (your relevant code wasn't posted, so this is just a guess)
CatsModel it = retrieveMyCustomAdapter();
becomes
BaseAdapter it = retrieveMyCustomAdapter();
A more formal approach would be to declare an abstract class extending BaseAdapter, and make both CatsModel and ArticlesModel inherit from this new class.
I am working on a application which require image and text group together in horizontal scroll bar.
I have tried few things but i am unable to get this, can anyone guide me with this guys.
Here is what i a have done,
main.xml
<?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">
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:scrollbars="horizontal" >
<GridView
android:layout_height="wrap_content"
android:id="#+id/gridView1"
android:layout_width="wrap_content"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:scrollbars="horizontal"
android:verticalSpacing="10dp">
</GridView>
</HorizontalScrollView>
</LinearLayout>
gridview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/border"
android:padding="5dp">
<ImageView
android:layout_height="64dp"
android:id="#+id/imageView1"
android:layout_width="64dp"
android:src="#drawable/icon"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ImageView>
<TextView
android:text="TextView"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_marginTop="2dp"
android:layout_centerHorizontal="true"
android:textSize="18sp"></TextView>
</RelativeLayout>
GridviewExampleActivity.java
package com.paresh.gridviewexample;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class GridViewExampleActivity extends Activity {
/** Called when the activity is first created. */
private GridviewAdapter mAdapter;
private ArrayList<String> listCountry;
private ArrayList<Integer> listFlag;
private GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(this,listCountry, listFlag);
// Set custom adapter to gridview
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(GridViewExampleActivity.this, mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
}
public void prepareList()
{
listCountry = new ArrayList<String>();
listCountry.add("india");
listCountry.add("Brazil");
listCountry.add("Canada");
listCountry.add("China");
listCountry.add("France");
listCountry.add("Germany");
listCountry.add("Iran");
listCountry.add("Italy");
listCountry.add("Japan");
listCountry.add("Korea");
listCountry.add("Mexico");
listCountry.add("Netherlands");
listCountry.add("Portugal");
listCountry.add("Russia");
listCountry.add("Saudi Arabia");
listCountry.add("Spain");
listCountry.add("Turkey");
listCountry.add("United Kingdom");
listCountry.add("United States");
listFlag = new ArrayList<Integer>();
listFlag.add(R.drawable.india);
listFlag.add(R.drawable.brazil);
listFlag.add(R.drawable.canada);
listFlag.add(R.drawable.china);
listFlag.add(R.drawable.france);
listFlag.add(R.drawable.germany);
listFlag.add(R.drawable.iran);
listFlag.add(R.drawable.italy);
listFlag.add(R.drawable.japan);
listFlag.add(R.drawable.korea);
listFlag.add(R.drawable.mexico);
listFlag.add(R.drawable.netherlands);
listFlag.add(R.drawable.portugal);
listFlag.add(R.drawable.russia);
listFlag.add(R.drawable.saudi_arabia);
listFlag.add(R.drawable.spain);
listFlag.add(R.drawable.turkey);
listFlag.add(R.drawable.united_kingdom);
listFlag.add(R.drawable.united_states);
}
}
GridviewAdapter.java
package com.paresh.gridviewexample;
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class GridviewAdapter extends BaseAdapter
{
private ArrayList<String> listCountry;
private ArrayList<Integer> listFlag;
private Activity activity;
public GridviewAdapter(Activity activity,ArrayList<String> listCountry, ArrayList<Integer> listFlag) {
super();
this.listCountry = listCountry;
this.listFlag = listFlag;
this.activity = activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listCountry.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listCountry.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public ImageView imgViewFlag;
public TextView txtViewTitle;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.gridview_row, null);
view.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
view.imgViewFlag = (ImageView) convertView.findViewById(R.id.imageView1);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtViewTitle.setText(listCountry.get(position));
view.imgViewFlag.setImageResource(listFlag.get(position));
return convertView;
}
}
My ouput should be
------------ ---------- ------------ ----
Image Image Image Image Image Image Image Image Image Image Image
Text Text Text Text Text Text Text Text Text Text Text
------------ ---------- ------------ --
Please Help me guys
Hi there just have a look at CustomArrayAdapter used for ListViews and Gridviews especially point 10 at this Tutoiral there you get to know how to customize your GridView/ListView (handled same way)
This might also help
If you have problems with the hotrizontal way, try this project: https://github.com/jess-anders/two-way-gridview
I want to create a tab dynamically in Android and under each tab I have one listview. So I want the content of the listview to also change dynamically. How can I do this ?
I saw a code on another forum and cleaned it up a little. To do what you need you'll have to change the stuff inside of ts1.setContent and ts2.setContent
Main_screen.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class Main_screen extends Activity{
private ListView ls1;
private ListView ls2;
private TabHost myTabHost;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
myTabHost = (TabHost)this.findViewById(R.id.th_set_menu_tabhost);
myTabHost.setup();
ls1 = new ListView(Main_screen.this);
TabSpec ts1 = myTabHost.newTabSpec("TAB_TAG_1");
ts1.setIndicator("Tab1");
ts1.setContent(new TabHost.TabContentFactory(){
public View createTabContent(String tag)
{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main_screen.this,android.R.layout.simple_list_item_1,new String[]{"item1","item2","item3"});
ls1.setAdapter(adapter);
return ls1;
}
});
myTabHost.addTab(ts1);
ls2 = new ListView(Main_screen.this);
TabSpec ts2 = myTabHost.newTabSpec("TAB_TAG_2");
ts2.setIndicator("Tab2");
ts2.setContent(new TabHost.TabContentFactory(){
public View createTabContent(String tag)
{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main_screen.this,android.R.layout.simple_list_item_1,new String[]{"item4","item5","item6"});
ls2.setAdapter(adapter);
return ls2;
}
});
myTabHost.addTab(ts2);
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/th_set_menu_tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="64dip" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="75dip">
<ListView
android:id = "#+id/danhsach"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>
</TabHost>
for(int i=0; i<5; i++ )
{
final TabSpec x=tabHost2.newTabSpec("x");
View row = inflater.inflate(R.layout.indicator1,null);
final TextView indicator1 =(TextView) row.findViewById(R.id.textView_indicator1);
indicator1.setText(indicator_list[i]);
// indicator1.setShadowLayer(1, 0, 1, 0xFF013201);
x.setIndicator(row);
x.setContent(new TabContentFactory() {
public View createTabContent(String arg) {
return gallery2;
}
});
tabHost2.addTab(x);
}
you can do like this.