I have created dynamically Table Layout. However, my Title Row pushes downward when other rows are dynamically created. I want to make the title stay at the top.
The XML code:
<LinearLayout 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=".FirstScreen"
android:orientation="vertical"
android:background="#color/white" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:text="Shopping Cart"
android:textColor="#898989"
android:textSize="17dp"
android:textStyle="bold" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/displayLinear"
android:layout_marginLeft="10dp"
android:background="#ffffff"
android:orientation="vertical" >
</TableLayout>
<Button
android:id="#+id/second"
style="#style/btnStyleShakespeare"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_marginRight="80dp"
android:layout_marginTop="10dp"
android:text="Checkout"
android:textColor="#ffffff" />
<Button
android:id="#+id/scanMore"
style="#style/btnStyleShakespeare"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_marginRight="80dp"
android:layout_marginTop="5dp"
android:text="Scan More"
android:textColor="#ffffff" />
</LinearLayout>
This is my dynamically created code.
package info.androidhive.slidingmenu;
public class ScreenFirstFragment extends Fragment {
public ScreenFirstFragment(){}
public static double pFinalPrice;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_firstscreen, container, false);
//final LinearLayout lm = (LinearLayout) rootView.findViewById(R.id.linearMain);
final Button secondBtn = (Button) rootView.findViewById(R.id.second);
final Button scanMoreBtn = (Button) rootView.findViewById(R.id.scanMore);
//Get Global Controller Class object (see application tag in AndroidManifest.xml)
final Controller aController = (Controller) getActivity().getApplicationContext();
/******* Create view elements dynamically and show on activity ******/
//Product arraylist size
int ProductsSize = aController.getProductsArraylistSize();
/******** Dynamically create view elements - Start **********/
TableLayout ll = (TableLayout) rootView.findViewById(R.id.displayLinear);
ll.setStretchAllColumns(true);
ll.setShrinkAllColumns(true);
TableRow rowProdLabels = new TableRow(this.getActivity());
// Product column
TextView prodLabel = new TextView(this.getActivity());
prodLabel.setText("PRODUCT");
prodLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
rowProdLabels.addView(prodLabel);
// Price column
TextView priceLabel = new TextView(this.getActivity());
priceLabel.setText("PRICE");
priceLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
rowProdLabels.addView(priceLabel);
// Quantity column
TextView quantityLabel = new TextView(this.getActivity());
quantityLabel.setText("Quantity");
quantityLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
rowProdLabels.addView(quantityLabel);
// Total column
TextView totalLabel = new TextView(this.getActivity());
totalLabel.setText("Total Price");
totalLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
rowProdLabels.addView(totalLabel);
ll.addView(rowProdLabels);
for(int j=0;j< ProductsSize;j++)
{
// Get probuct data from product data arraylist
String pName = aController.getProducts(j).getProductName();
double pPrice = aController.getProducts(j).getProductPrice();
int pQuantity = aController.getProducts(j).getProductQuantity();
double pTotalPrice = pPrice * pQuantity;
TableRow row= new TableRow(this.getActivity());
TextView product = new TextView(this.getActivity());
product.setText(pName+" ");
//Add textView to LinearLayout
row.addView(product);
TextView price = new TextView(this.getActivity());
price.setText("RM "+pPrice+" ");
//Add textView to LinearLayout
row.addView(price);
TextView quantity = new TextView(this.getActivity());
quantity.setText(pQuantity+" ");
//Add textView to LinearLayout
row.addView(quantity);
TextView totalprice = new TextView(this.getActivity());
totalprice.setText(String.format("RM %.2f",pTotalPrice));
//Add textView to LinearLayout
row.addView(totalprice);
//Update final price
pFinalPrice += pTotalPrice;
ll.addView(row,j);
}
/******** Dynamically create view elements - End **********/
secondBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FragmentTransaction mFragmentTransaction = getFragmentManager().beginTransaction();
mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
mFragmentTransaction.replace(R.id.frame_container, new ScreenSecondFragment(), "Cart");
mFragmentTransaction.commit();
}
});
scanMoreBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FragmentTransaction mFragmentTransaction = getFragmentManager().beginTransaction();
mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
mFragmentTransaction.replace(R.id.frame_container, new ScanFragment(), "Scan Product");
mFragmentTransaction.commit();
}
});
return rootView;
}
}
Related
In my fragment, I want each custom item in my listview to look as follows:
Name
SetsXReps
[][][][][] ---> array of textviews
[][][][][] ---> array of checkboxes
The number of textviews and checkboxes depends upon the item in the adapter, so I need to create that part dynamically. I am having trouble adding these elements dynamically to my relativelayout that I partially define in my xml. Here is my fragment class followed by my xml for the custom list item. The id for the layout is list_item_exercise_in_workout.
public class WorkoutFragment extends Fragment
{
public static final String EXTRA_ALREADYCREATED_ID = "shake2lift.nickdelnano.com";
private ExAdapter adapter;
private ListView listView;
private ArrayList<Set> sets;
private Workout w;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID workoutId = (UUID) getArguments().getSerializable(EXTRA_ALREADYCREATED_ID);
w = WorkoutMASTER.get(getActivity()).getWorkout(workoutId);
}
public View onCreateView(LayoutInflater inflater, ViewGroup parent,Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_workout, parent, false);
adapter = new ExAdapter(getActivity(), R.layout.fragment_create_workout, R.id.list, sets);
listView.setAdapter(adapter);
return v;
}
public static WorkoutFragment newInstance(UUID workoutId)
{
Bundle args = new Bundle();
args.putSerializable(EXTRA_ALREADYCREATED_ID, workoutId);
WorkoutFragment fragment = new WorkoutFragment();
fragment.setArguments(args);
return fragment;
}
private class ExAdapter extends ArrayAdapter<Set>
{
public ExAdapter(Context c, int resource, int textViewResourceId, ArrayList<Set> sets ) {
super(c, 0, sets);
}
public View getView(final int position, View convertView, ViewGroup parent)
{
//if we werent given a view, inflate one
if(convertView == null)
{
convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_exercise_in_workout, null);
}
Set s = getItem(position);
//RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
// RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT );
TextView name = (TextView) convertView.findViewById(R.id.exName);
name.setText(s.getName());
TextView setsReps = (TextView) convertView.findViewById(R.id.setsXreps);
setsReps.setText(s.getSets() + "X" + s.getReps());
CheckBox[] checkBoxes = new CheckBox[s.getSetsInt()];
EditText[] weightBoxes = new EditText[s.getSetsInt()];
//initialize weightBoxes's text to the inputted weight
for(int i = 0; i < weightBoxes.length; i++)
{
//code to add dynamically here
}
return convertView;
}
}
}
and my XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/relativeLayoutEx"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Name"
android:id="#+id/exName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="SetsXReps"
android:id="#+id/setsXreps"
android:layout_below="#id/exName"
android:layout_alignParentLeft="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button2"
android:layout_below="#+id/setsXreps"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="112dp" />
I appreciate any help or advice.
You need to first get a pointer to your RelativeLayout like this
RelativeLayout container = (RelativeLayout) view.findViewById(R.id.relativeLayoutEx);
Then in your for loop, create the Text Boxes (and Check Boxes) dynamically and add them to the layout:
TextView text = new TextView(getActivity());
text.setText("Hello");
container.addView(text);
When I run my program I get the error E/AndroidRuntime(27275): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. where is the problem??
My list fragment class
package com.zaa.yhgj;
public class HomeFragment extends ListFragment {
private List<ListViewItem> mItems; // ListView items list
View myFragmentView;
ArrayList<View> chart_view = new ArrayList<View>();
List<Integer> onedimen = new ArrayList<Integer>();
List<List> aa = new ArrayList<List>();
///
List<List> statuslistoflist = new ArrayList<List>();
List<String> statusonedimen = new ArrayList<String>();
private List<DialogInterface.OnClickListener> nItems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.dashboardlist, container, false);
HashMap<String,Integer> myhash=new HashMap<String, Integer>() ;
myhash.put("Pending",0);
myhash.put("In Progress",0);
myhash.put("Limitation",0);
myhash.put("Needs Research",0);
myhash.put("In Testing",0);
myhash.put("Issue Not Clear",0);
myhash.put("Unassigned",0);
int mainclasssize = Constants.listuserprojectMain.getMainListClass().size();
int[] listsize = new int[mainclasssize];
String[] projectname = new String[mainclasssize];
int[] openissuecount = new int[mainclasssize];
for (int k = 0; k < mainclasssize; k++) {
listsize[k] = Constants.listuserprojectMain.getMainListClass().get(k).getProjectIssue().size();
projectname[k] = Constants.listuserprojectMain.getMainListClass().get(k).getName();
openissuecount[k] = Constants.listuserprojectMain.getMainListClass().get(k).getOpenIssueCount();
}
for (int w = 0; w < mainclasssize; w++) {
onedimen = new ArrayList<Integer>();
for (int x = 0; x < listsize[w]; x++) {
myhash.put(Constants.listuserprojectMain.getMainListClass().get(w).getProjectIssue().get(x).getStatus(),Constants.listuserprojectMain.getMainListClass().get(w).getProjectIssue().get(x).getIssueCount());
}
Set keys = myhash.keySet();
Iterator itr = keys.iterator();
String key;
int value;
while(itr.hasNext())
{
key = (String)itr.next();
onedimen.add((Integer)myhash.get(key));
value = (Integer)myhash.get(key);
// System.out.println(key + " - "+ value);
}
aa.add(onedimen);
statuslistoflist.add(statusonedimen);
}
for (int v = 0; v < aa.size(); v++) {
chart_view.add(openChart(aa.get(v)));
}
mItems = new ArrayList<ListViewItem>();
nItems = new ArrayList<DialogInterface.OnClickListener>();
Resources resources = getResources();
for (int f = 0; f < aa.size(); f++) {
mItems.add(new ListViewItem(projectname[f], openissuecount[f], chart_view.get(f)));
}
nItems.add(new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
// initialize and set the list adapter
setListAdapter(new ListViewDemoAdapter(getActivity(), mItems));
return myFragmentView;
}
private View openChart(List<Integer> chartvaluedd) {
return v;
}
}
my adapter class is
public class ListViewDemoAdapter extends ArrayAdapter {
public ListViewDemoAdapter(Context context, List<ListViewItem> items) {
super(context, R.layout.dashboardlistview_item, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder= new ViewHolder();
if(convertView == null) {
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.dashboardlistview_item, parent, false);
// initialize the view holder
// viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
viewHolder.graphView = (LinearLayout) convertView.findViewById(R.id.ll_chart);
viewHolder.tvCreateIssue = (TextView) convertView.findViewById(R.id.tvCreateissue);
viewHolder.tvDetails = (TextView) convertView.findViewById(R.id.tv_details);
viewHolder.tvIssue = (TextView) convertView.findViewById(R.id.tv_issues);
viewHolder.tvProjectTitle = (TextView) convertView.findViewById(R.id.tv_projectTitle);
viewHolder.tvOpenIssueCount = (TextView) convertView.findViewById(R.id.tv_openissues);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
// recycle the already inflated view
///error when scrolling graph
viewHolder.graphView.removeAllViews();
}
// update the item view
final ListViewItem item = getItem(position);
viewHolder.tvCreateIssue.setText("Create Issue");
viewHolder.tvProjectTitle.setText(item.title);
viewHolder.graphView.addView(item.chartview);
viewHolder.tvOpenIssueCount.setText("Open Issues "+item.openissuecount);
viewHolder.tvCreateIssue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), item.title, Toast.LENGTH_SHORT).show();
}
});
/////
viewHolder.tvIssue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(),"issue",Toast.LENGTH_LONG).show();
}
});
return convertView;
}
private static class ViewHolder {
// ImageView ivIcon;
LinearLayout graphView;
TextView tvCreateIssue;
TextView tvDetails;
TextView tvProjectTitle;
TextView tvOpenIssueCount;
TextView tvIssue;
}
}
my xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<include layout="#layout/top" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="none" >
</ListView>
</LinearLayout>
my listview item is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center_vertical"
android:background="#color/list_background"
android:padding="5dp"
android:id="#+id/ww"
>
<!-- the innner view - provides the white rectangle -->
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:background="#drawable/frame"
android:id="#+id/jhhh">
<!-- the icon view -->
<TextView
android:id="#+id/tv_projectTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Project name"
android:textSize="16dp"
android:textStyle="bold"
android:layout_centerHorizontal="true"
/>
<LinearLayout android:id="#+id/ll_chart"
android:orientation="vertical"
android:layout_below="#+id/tv_projectTitle"
android:layout_width="wrap_content"
android:layout_height="230dp"
android:background="#ffffff"
android:padding="5dp"
android:scaleType="fitXY" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ll_chart"
android:id="#+id/tv_openissues"
android:text="Open Issues 24"/>
<LinearLayout
android:layout_width="wrap_content"
android:id="#+id/ll_textview"
android:padding="5dp"
android:layout_alignParentRight="true"
android:layout_below="#id/tv_openissues"
android:orientation="horizontal"
android:layout_height="wrap_content">
<TextView android:id="#+id/tvCreateissue"
android:drawableLeft="#drawable/bug6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create Issue"
/>
<!-- the description view -->
<TextView android:id="#+id/tv_details"
android:layout_below="#id/tvCreateissue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/bars64"
android:layout_marginLeft="5dp"
android:text="Details"
/>
<TextView android:id="#+id/tv_issues"
android:layout_below="#id/tvCreateissue"
android:layout_marginLeft="5dp"
android:drawableLeft="#drawable/bug6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Issues"
/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
I might be wrong, but the error seems to reside here:
viewHolder.graphView.addView(item.chartview);
Once the view item.chartview is added to graphView, it has a parent. However ListView is known to call some getView on some positions multiple times for caching.
It would seem that the same view is being added to multiple parents which in return throws the error you get. Before adding the chartview you could try removing it from its parent if it exists:
// Remove from parent (if exists)
ViewGroup parent = item.chartview.getParent();
if (parent != null) {
parent.removeView(item.chartview);
}
// Add to another parent
viewHolder.graphView.addView(item.chartview);
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.dashboardlist, container, false);
instead of container use null
(I'm not an android geek but faced the problem before)
I have a layout and i need to insert into in some kind of blocks with text - like comments date, name, text. Is there a way to use it like this
for (int r=0; r<10;r++) {
TextView t1=(TextView) findviewbyid(R.id.text1);
t1="BlaBla";
mainlayout.add(commentLayout);
}
So i get something like listview but without adapter and etc.
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:id="#+id/comm_name"
android:layout_marginLeft="20dp"
android:layout_marginTop="24dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date"
android:id="#+id/comm_date"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_margin="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="60dp"
android:layout_marginLeft="20dp"
android:id="#+id/comm_text" />
you can do it, but the way you are doing it will throw an exception, because findViewById returns always the same object, and after the first iteration t1 has already a parent. You should create a new instance of the TextView programmatically, at every iteration.
Try adding views dynamically in linear layout which is inside scroll view.
Try this code.I know it is not exact solution.But,Hope it gives you some idea.
public class MainActivity extends Activity {
ScrollView scrollview;
LinearLayout linearLayout;
LinearLayout.LayoutParams layoutParams;
static int i;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrollview = (ScrollView)findViewById(R.id.scrollview);
linearLayout = (LinearLayout)findViewById(R.id.linearlayout);
Button button = (Button)findViewById(R.id.button);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView view = new TextView(MainActivity.this);
view.setText(++i+" view");
linearLayout.addView(view, layoutParams);
}
});
}}
Use Following approach
Looping to add dynamically Views to Linear Layout
TextView textView1, textView2;
LinearLayout completeLinearLayout = (LinearLayout) findViewById(R.id.ll);
for (int i = 0; i < 10; i++) {
textView1 = new TextView(Activity.this);
textView2 = new TextView(Activity.this);
String name1 = "xyz";
String name2 = "abc"
completeLinearLayout.addView(textView1);
completeLinearLayout.addView(textView2);
setTextViewParam(textView1, name1);
setTextViewParam(textView2, name2);
}
Method to set TextView Parameters Dynamically
private void setTextViewParam(TextView tv, String text) {
LayoutParams textLayoutParams = new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
textLayoutParams.setMargins(5, 0, 0, 0);
tv.setGravity(Gravity.LEFT);
tv.setText(text);
tv.setTextSize(13);
tv.setTextColor(Color.BLACK);
tv.setLayoutParams(textLayoutParams);
}
Now you can customize the views according to need and container as well.
Happy Coding!!
So, this code works exactlay as i need.
Is there anything wrong with it??
public class InflateView extends Activity {
LinearLayout lLayout;
TextView t,f;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
lLayout = (LinearLayout)findViewById(R.id.layout1);
for (int i=0;i<10;i++)
{
RelativeLayout tv = (RelativeLayout)inflater.inflate(R.layout.text, null);
lLayout.addView(tv);
t = (TextView) tv.findViewById(R.id.ttt);
t.setText("aaaaaaa" + i) ;
f = (TextView) tv.findViewById(R.id.textView);
f.setText(String.valueOf(i));
}
}}
(SOLVED) -- Removed layout params on each view ---
I am new to Android and I am trying to add rows in a TableLayout from the items that I entered in text fields.
(EDITED) Here's my layout for this Fragment:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:tag="contacts">
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/contactName"
android:hint="Name"
android:paddingTop="5dip" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/contactRelationship"
android:hint="Relationship"
android:paddingTop="5dip" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:ems="10"
android:id="#+id/contactAddress"
android:hint="Address"
android:paddingTop="5dip" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/contactPhoneNo"
android:hint="Phone Number"
android:paddingTop="5dip" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/contactPhoneTypeSpinner"
android:layout_toEndOf="#+id/contactPhoneNo"
android:layout_toRightOf="#+id/contactPhoneNo"
android:paddingTop="5dip" />
</RelativeLayout>
<EditText
android:layout_width="match_parent"
android:layout_height="107dp"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/contactSpecialNotes"
android:paddingTop="5dip"
android:hint="Write special notes here" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Contact"
android:id="#+id/addContact" />
<TableLayout
android:id="#+id/contactsTableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dip"></TableLayout>
</LinearLayout>
</ScrollView>
(EDITED)Here's the code for this Fragment:
public static class ContactsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_contacts,
container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Spinner phoneTypeSpinner = (Spinner) this.getView().findViewById(R.id.contactPhoneTypeSpinner);
Button contactButton = (Button) this.getView().findViewById(R.id.addContact);
final TableLayout tableLayout = (TableLayout) this.getView().findViewById(R.id.contactsTableLayout);
final EditText txtContactName = (EditText) this.getView().findViewById(R.id.contactName);
final EditText txtContactRelationship = (EditText) this.getView().findViewById(R.id.contactRelationship);
final EditText txtContactAddress = (EditText) this.getView().findViewById(R.id.contactAddress);
final EditText txtContactPhoneNo = (EditText) this.getView().findViewById(R.id.contactPhoneNo);
Spinner contactPhoneTypeSpinner = (Spinner) this.getView().findViewById(R.id.contactPhoneTypeSpinner);
EmployeeDataSource datasource = new EmployeeDataSource(getActivity());
datasource.open();
//--- Gender Spinner ---
List<PhoneType> list = datasource.getPhoneTypeList();
ArrayAdapter<PhoneType> adapter = new ArrayAdapter<PhoneType>(getActivity(),
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
phoneTypeSpinner.setAdapter(adapter);
phoneTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
contactButton.setOnClickListener(new View.OnClickListener() {
int rowId = 0;
#Override
public void onClick(View v) {
TableRow tableRow = new TableRow(getActivity().getApplicationContext());
tableRow.setId(rowId++);
tableRow.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
TextView tvContactName = new TextView(getActivity().getApplicationContext());
tvContactName.setText(txtContactName.getText().toString());
tvContactName.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
tableRow.addView(tvContactName);
TextView tvRelationship = new TextView(getActivity().getApplicationContext());
tvRelationship.setText(txtContactRelationship.getText().toString());
//tvRelationship.setLayoutParams(new ViewGroup.LayoutParams(
// ViewGroup.LayoutParams.FILL_PARENT,
// ViewGroup.LayoutParams.WRAP_CONTENT));
tableRow.addView(tvRelationship);
TextView tvContactNo = new TextView(getActivity().getApplicationContext());
tvContactNo.setText(txtContactPhoneNo.getText().toString());
//tvContactNo.setLayoutParams(new ViewGroup.LayoutParams(
// ViewGroup.LayoutParams.FILL_PARENT,
// ViewGroup.LayoutParams.WRAP_CONTENT));
tableRow.addView(tvContactNo);
tableLayout.addView(tableRow, new TableLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
});
}
}
I could see in the debugger that the values from my views were added in my tableRow but I don't see the table appearing in my screen, what am I missing or doing wrong?
Any help would be greatly appreciated.
Thanks!
I guess the height of screen is increased. Try using Scrollview on top of this layout.
I think you have to change RelativeLayout property android:height="wrap_content" instead of android:height="fill_parent" and also do for TableLayout
May this work for you...
Try this:
Edited:
public static class ContactsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_contacts,
container, false);
Spinner phoneTypeSpinner = (Spinner) rootView.findViewById(R.id.contactPhoneTypeSpinner);
Button contactButton = (Button) rootView.findViewById(R.id.addContact);
final TableLayout tableLayout = (TableLayout) rootView.findViewById(R.id.contactsTableLayout);
final EditText txtContactName = (EditText) rootView.findViewById(R.id.contactName);
final EditText txtContactRelationship = (EditText) rootView.findViewById(R.id.contactRelationship);
final EditText txtContactAddress = (EditText) rootView.findViewById(R.id.contactAddress);
final EditText txtContactPhoneNo = (EditText) rootView.findViewById(R.id.contactPhoneNo);
Spinner contactPhoneTypeSpinner = (Spinner) rootView.findViewById(R.id.contactPhoneTypeSpinner);
EmployeeDataSource datasource = new EmployeeDataSource(getActivity());
datasource.open();
//--- Gender Spinner ---
List<PhoneType> list = datasource.getPhoneTypeList();
ArrayAdapter<PhoneType> adapter = new ArrayAdapter<PhoneType>(getActivity(),
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
phoneTypeSpinner.setAdapter(adapter);
phoneTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
contactButton.setOnClickListener(new View.OnClickListener() {
int rowId = 0;
#Override
public void onClick(View v) {
TableRow tableRow = new TableRow(getActivity().getApplicationContext());
tableRow.setId(rowId++);
TextView tvContactName = new TextView(getActivity().getApplicationContext());
tvContactName.setText(txtContactName.getText().toString());
tableRow.addView(tvContactName);
TextView tvRelationship = new TextView(getActivity().getApplicationContext());
tvRelationship.setText(txtContactRelationship.getText().toString());
tableRow.addView(tvRelationship);
TextView tvContactNo = new TextView(getActivity().getApplicationContext());
tvContactNo.setText(txtContactPhoneNo.getText().toString());
tableRow.addView(tvContactNo);
tableLayout.addView(tableRow, new TableLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
I'm having a listview in which I'm displaying the text items. I want to display a checkbox along with the text for two type of actions to be performed. one is when the user click on the list item it should take to another activity and another is the user can select the checkbox of the list item and can move the items to some groups. As similar to that we do in the gmail inbox. how can i do it ? Any help ?
Here I attach my code.
keywords.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/keywordlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_gradient"
android:orientation="vertical"
>
<LinearLayout
android:id="#+id/category_title_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#fff"
>
<TextView
android:id="#+id/category_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:textColor="#000"
android:textStyle="italic"
android:typeface="sans"
android:gravity="center"
/>
</LinearLayout>
<ListView
android:id="#+id/keywordslist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_gradient"
>
</ListView>
</LinearLayout>
The xml file used for displaying list items layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_display"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<CheckBox
android:id="#+id/chk_box"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:visibility="invisible"
>
</CheckBox>
<TextView
android:id="#+id/key_id"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
>
</TextView>
<TextView
android:id="#+id/key_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:textColor="#FFF">
</TextView>
</LinearLayout>
and my java code for the activity
package com.sample.epiphron;
public class KeywordsList extends Activity {
TextView category_title;
ListView keywords_list ;
String categoryid, categoryname;
private ArrayList<KeywordDetails> listItems = new ArrayList<KeywordDetails>();
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.keywords);
Bundle extras = getIntent().getExtras();
categoryid = extras.getString("category_id");
categoryname = extras.getString("category_name");
category_title = (TextView) findViewById(R.id.category_title);
category_title.setText(""+categoryname+"- Keywords");
keywords_list = (ListView) findViewById(R.id.keywordslist);
drawList(LoginScreen.user_credential, categoryid);
//Toast.makeText(this, chkbx.toString(), Toast.LENGTH_SHORT).show();
keywords_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView txtv1 = (TextView) arg1.findViewById(R.id.key_id);
Toast.makeText(KeywordsList.this, txtv1.getText(), Toast.LENGTH_LONG).show();
}
});
}
public void drawList(String userid, String cat_id){
WebServiceCall res = new WebServiceCall();
SoapObject result = res.fetchKeyword(userid, cat_id);
ArrayList<String> al = new ArrayList<String>();
for (int i = 0; i<result.getPropertyCount(); i++){
SoapObject obj = (SoapObject) result.getProperty(i);
al.add((String) obj.getProperty("keywordname"));
KeywordDetails object = new KeywordDetails(Integer.parseInt(obj.getProperty("keywordid").toString()), obj.getProperty("keywordname").toString());
listItems.add(object);
}
for ( int j = 0; j < result.getPropertyCount(); j++ ) {
}
keywords_list.setAdapter(new ListItemsAdapter(listItems));
}
public class KeywordDetails{
private int keyword_id;
private String keyword_name;
public KeywordDetails(int key_id, String key_name){
this.keyword_id = key_id;
this.keyword_name = key_name;
}
public int getId(){
return this.keyword_id;
}
public String getName(){
return this.keyword_name;
}
//...
}
private class ListItemsAdapter extends ArrayAdapter<KeywordDetails> {
ArrayList<KeywordDetails> obj = null;
KeywordDetails keyworddtls = null;
public ListItemsAdapter(ArrayList<KeywordDetails> items) {
super(KeywordsList.this, android.R.layout.simple_list_item_1, items);
this.obj = items;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.keyword_list_item, null);
final TextView text1 = (TextView) convertView.findViewById(R.id.key_id);
TextView text2 = (TextView) convertView.findViewById(R.id.key_name);
CheckBox chkbx = (CheckBox) convertView.findViewById(R.id.chk_box);
keyworddtls = obj.get(position);
text1.setText(Integer.toString(keyworddtls.getId()));
text2.setText(keyworddtls.getName());
chkbx.setVisibility(View.VISIBLE);
return convertView;
}
}
}
Add the CheckBox in the xml where is your <ListView > or in the xml which you use as item layout. Then in the getView() instantiate the CheckBox along the TextView. Implement listview.setOnItemClickListener() and based on which item was clicked (position) you start the activity [matter of logic] For the grouped of check items you can use getCheckedItemPositions(). I hope this will give you fire up idea.