How to get data from dynamically created EditText using LayoutInflater in android? - android

This is Relative Layout view which is created dynamically like this :
...
So my question is how to get the values from those dynamic elements and perform some calculation to show result on textview which is also dynamically created.
Thanks in advance guys!!
public void goButtonClicked(View view) {
maalContainer.removeAllViews();
int numberofPlayersTolayout = (Integer) Integer.parseInt((String) numberOfPlayers.getSelectedItem());
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
for (int i = 0; i < numberofPlayersTolayout; i++) {
View dynamicEntryView = inflater.inflate(R.layout.player_entry_item, null);
maalContainer.addView(dynamicEntryView, params);
}
}
}

for (int i = 0; i < maalContainer.getChildCount(); i++) {
View view = maalContainer.getChildAt(i);
EditText ed_item = (EditText) view
.findViewById(R.id.edittext1);
EditText ed_value = (EditText) view
.findViewById(R.id.edittext2);
EditText ed_value1 = (EditText) view
.findViewById(R.id.edittext3);
ed_item.getText().toString().trim();
ed_value.getText().toString().trim();
ed_value1.getText().toString().trim();
}

No need to assign/get ID of any View but the best way is to iterate through the child views of LinearLayout:
int childcount = myLinearLayout.getChildCount();
for (int i=0; i < childcount; i++){
View v = myLinearLayout.getChildAt(i);
// do whatever you would want to do with this View
}

A few things here:
You shouldn't be using the Application Context to get the LayoutInflater. You should get that from the Activity Context, otherwise your themes and styles will not be respected.
You shouldn't inflate with null as the second parameter (except in special instances where you don't know the View's parent). Just put the android:layout_width="match_parent" and android:layout_height="wrap_content" attributes in player_entry_item.xml and they will be respected upon inflation.
Store the EditText objects upon inflation as a private array.
With that said, my suggested revision:
private EditText[] mEditTextPlayers;
public void goButtonClicked(View view) {
maalContainer.removeAllViews();
int numPlayers = Integer.parseInt((String) numberOfPlayers.getSelectedItem());
LayoutInflater inflater = LayoutInflater.from(view.getContext());
mEditTextPlayers = new EditText[numPlayers];
for (int i = 0; i < numPlayers; i++) {
//Pass the parent as the second parameter to retain layout attributes
mEditTextPlayers[i] = inflater.inflate(R.layout.player_entry_item, maalContainer, false);
maalContainer.addView(dynamicEntryView);
}
}

public void goButtonClicked(View view) {
int numberofPlayersTolayout = Integer.parseInt(numberOfPlayers.getSelectedItem().toString());
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
maalContainer.removeAllViews();
maalText = new EditText[numberofPlayersTolayout];
points = new EditText[numberofPlayersTolayout];
result = new TextView[numberofPlayersTolayout];
for (int i = 0; i < numberofPlayersTolayout; i++) {
View dynamicEntryView = inflater.inflate(R.layout.player_entry_item, null);
maalContainer.addView(dynamicEntryView, params);
TextView playerName = (TextView) dynamicEntryView.findViewById(R.id.player_name_textview);
playerName.setText("Player :" + (i + 1));
maalText[i] = (EditText) dynamicEntryView.findViewById(R.id.player_item_edittext_maal);
points[i] = (EditText) dynamicEntryView.findViewById(R.id.player_item_edittext_point);
result[i] = (TextView) dynamicEntryView.findViewById(R.id.player_item_textview_result);
}

You can do it by using getId() and setId() methods of the View.
dynamicEntryView.setId(i);
and access the view as below by getting the
dynamicEntryView.getId(i);

<?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" >
<TextView
android:id="#+id/player_name_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10sp"
android:layout_marginTop="10sp"
android:text="Player name"
android:textColor="#202020"
android:textSize="18sp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<EditText
android:id="#+id/player_item_edittext_point"
android:layout_width="0sp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Points"
android:inputType="number"
android:textColor="#202020" />
<EditText
android:id="#+id/player_item_edittext_maal"
android:layout_width="0sp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Maal"
android:inputType="number"
android:textColor="#202020" />
<TextView
android:id="#+id/player_item_textview_result"
android:layout_width="0sp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="0.00$"
android:textSize="22sp"
android:typeface="serif" />
</LinearLayout>
</LinearLayout>
Only one id is used. It will loop through according to number of players. Hope it will help you. #user2731584

Related

How to get the total number of Views in a lyout including subviews

I am trying to count all the views in any layout being displayed to the user. To achieve it, the code posted below was used, but as you see in the layout, it contains
Button
LinearLayout
Button
Button
TextView
LinearLayout
when the code is executed, it says that the layout has only 4 widgets "Button, LinearLayout, TextView, LinearLayout", while I expected the code to return 6 widgets.
would you please tell me how to get the total widgets contains in a layout including the sub-widgets/views?
code:
public class ActMain extends AppCompatActivity {
private static final String TAG = ActMain.class.getSimpleName();
private LinearLayout mMainContainer = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
this.mMainContainer = (LinearLayout) findViewById(R.id.actMain_mainContainer);
int totalWidgets = this.mMainContainer.getChildCount();
Log.d(TAG, "totalWidgets:" + totalWidgets);
for (int i = 0; i < this.mMainContainer.getChildCount(); i++) {
View view = mMainContainer.getChildAt(i);
}
}
}
layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/actMain_mainContainer"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.alten.test_traversethroughaview_1.ActMain">
<Button
android:id="#+id/actMain_btn_change"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/decision_change" />
<LinearLayout
android:id="#+id/actMain_linlay_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/actMain_btn_yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/decision_yes" />
<Button
android:id="#+id/actMain_btn_no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/decision_no" />
</LinearLayout>
<TextView
android:id="#+id/actMain_tv_display"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/actMain_linlay_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
use this method:
public int getChildrenViews(ViewGroup parent){
int count = parent.getChildCount();
for (int i=0;i<parent.getChildCount();i++){
if (parent.getChildAt(i) instanceof ViewGroup){
count+=getChildrenViews((ViewGroup) parent.getChildAt(i));
}
}
return count;
}
anywhere you want add this part:
if (getWindow().getDecorView().getRootView() instanceof ViewGroup){
getChildrenViews((ViewGroup) getWindow().getDecorView().getRootView());
}
This function will probably help:
private int countChild(View view) {
if (!(view instanceof ViewGroup))
return 1;
int counter = 0;
ViewGroup viewGroup = (ViewGroup) view;
for (int i=0; i<viewGroup.getChildCount(); i++) {
counter += countChild(viewGroup.getChildAt(i));
}
return counter;
}
It only counts the leaves (ignores the ViewGroups). But if you want to count also them if is straightforward: just substitute counter = 0 with counter = 1.
Your code only counting its parent child, not all the child in the layout. That means you are counting Grandfather's child not Grandfather's Grandchild. You have to traverse all view to count all child. To do that you can use a recursive function to count all child.
getChildCount(View)
count = 1;
check the view is instance of ViewGroup
if it is ViewGroup
for each child
count+= getChildCount(child)
return count
Call this with root layout
totalChild = getChildCount(root)
Hope you can count all child this way.

Listview - Getview called multiple times

I have a ListView and a custom adapter. Now i have red posts about getView() method being called multiple times, and most of them have to do with the wrap_content feature of the ListView.
I have changed my height, so that it can be match_parent but still, the method is being called.
I think it has something to do with adding TextViews dynamically in the adapter, and i don't know how to do it, so it works properly.
If there is an alternative, i am opened to it, the only reason why i put TextViews is so that i can have letters written in different colors.
Here is my code:
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
Row current = mList.get(position);
/* if the given channel row view is not being updated*/
if (v == null)
{
/* inflate layout */
LayoutInflater vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.list_item2, null,false);
}
v = setLinearLayout(v,current);
return v;
}
Here is the setLinearLayout() method:
private View setLinearLayout(View v,Row current) {
ArrayList<Integer> winResults = current.checkNumbers(mResult,mType);
int numbers[] = current.getNumbers();
int N = Global.getNumberOfNumbers(mType);
boolean FLAG_SET = false;
final TextView[] myTextViews = new TextView[N]; // create an empty array;
for (int i = 0; i < N; i++) {
Log.d("PAVLE",""+i+" row is: "+current.getStringNumbers());
// create a new textview
final TextView rowTextView = new TextView(v.getContext());
LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,75);
rowTextView.setTextSize(24.0f);
rowTextView.setPadding(8, 8, 8, 8);
rowTextView.setGravity(Gravity.CENTER);
rowTextView.setBackgroundColor(Color.BLACK);
rowTextView.setTypeface(null, Typeface.BOLD);
rowTextView.setLayoutParams(lp);
if(mType == R.string.sans_topu && i == 5 && !FLAG_SET){
i--;
rowTextView.setTextColor(Color.WHITE);
rowTextView.setText("+");
FLAG_SET = true;
}
else {
// set some properties of rowTextView or something
if (mWin == Global.WIN || mWin == Global.LOSE) {
if (winResults.contains(numbers[i]))
rowTextView.setTextColor(Color.GREEN);
else rowTextView.setTextColor(Color.RED);
} else {
rowTextView.setTextColor(Color.WHITE);
}
if (numbers[i] < 10) {
rowTextView.setText("0" + numbers[i]);
} else rowTextView.setText("" + numbers[i]);
}
// add the textview to the linearlayout
LinearLayout ll = (LinearLayout) v.findViewById(R.id.ll_item);
ll.addView(rowTextView);
// save a reference to the textview for later
myTextViews[i] = rowTextView;
}
final TextView prize = new TextView(v.getContext());
LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,75);
prize.setTextSize(24.0f);
prize.setPadding(8, 8, 8, 8);
prize.setGravity(Gravity.CENTER);
prize.setBackgroundColor(Color.BLACK);
prize.setTypeface(null, Typeface.BOLD);
prize.setTextColor(Color.WHITE);
prize.setLayoutParams(lp);
try {
String cash = findCorretAmmount(winResults, numbers);
prize.setText(cash);
mTotal.append(" "+cash);
}
catch (Exception e){
e.printStackTrace();
}
LinearLayout ll = (LinearLayout) v.findViewById(R.id.ll_item);
ll.addView(prize);
return v;
}
And a little bit of XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tvRandomTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:paddingRight="8dp"
android:text="#string/your_ticket_numbers_"
android:textColor="#android:color/black"
android:textSize="28sp"
android:textStyle="bold"
/>
<View
android:id="#+id/divider4"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#id/tvRandomTextView"
android:layout_marginBottom="4dp"
android:layout_marginTop="4dp"
android:background="#android:color/darker_gray"/>
<ListView
android:id="#+id/lvRowList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/divider4"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
>
<Button
android:id="#+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="#string/delete"/>
<Button
android:id="#+id/btnShare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/btn_share"/>
<Button
android:id="#+id/btnDone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="#string/done"/>
</RelativeLayout>
<TextView
android:id="#+id/tvResultLink"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="4dp"
android:layout_marginTop="4dp"
android:autoLink="web"
android:gravity="center"
android:linksClickable="true"
/>
Also worth mentioning is that list_item2(LinearLayout) has height of 100dp, it's fixed size.
I think its not about textview.
The getView is always called multiple times. If you have 10 items on the screen to be shown, the getView going to be called 15 times, because the android creating views that are not on the screen. It`s good, because when the user start scrolling, it is not going to lagging.
After the user left the item, the view get`s recycle and reused by the adapter. Lets say, you have a list with 10000000 item, but you have 5 item on the screen at all time. In this case - to save power, and improve performance - the android going to create 10 list item, and this 10 item is going to recylce and refresh by content.
ViewHolder pattern
Please read this and use this patter to improve your code performance:
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
Google about ListView:
http://developer.android.com/guide/topics/ui/layout/listview.html
Tutorials:
http://developer.xamarin.com/guides/android/user_interface/working_with_listviews_and_adapters/

Handling Dynamically added Table Rows xml Layout in TableLayout Android

I have a TableLayout in fragment with following code:
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/projectsTableLayout"
android:orientation="vertical"
android:layout_margin="10dp">
</TableLayout>
This is the AddMore button which is below the TableLayout tag:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/buttonBarButtonStyle"
android:id="#+id/add_more_projects_btn"
android:text="#string/addmore"
android:textColor="#color/colorAccent"
android:layout_below="#+id/projectsTableLayout"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"/>
Also I have created TableRow layout in separate xml file with following code:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:orientation="vertical">
<EditText
android:id="#+id/project_name__ET"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginTop="10dp"
android:gravity="center_vertical"
android:hint="#string/projectnametxt"
android:inputType="text"
android:paddingLeft="5dp"
android:paddingRight="5dp" />
<LinearLayout
android:id="#+id/yearProjectTypeLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="05dp"
android:orientation="horizontal"
android:weightSum="1">
<Spinner
android:id="#+id/yearSpinner"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:drawSelectorOnTop="false"
android:spinnerMode="dropdown" />
<Spinner
android:id="#+id/projectTypeSpinner"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:drawSelectorOnTop="false"
android:spinnerMode="dropdown" />
</LinearLayout>
</LinearLayout>
</TableRow>
What I want to implement is when the application loads I will be dynamically add rows 5 times.
I want to add 5 more rows on the Add More button click. Also I have to send all the values to the webserver when the user moves ahead in the application.
I am confused how should provide the ID to the components like(EditText, Spinners) in the Rows of table and retrieve it when the user moves to next screen.
I want to code in such a way so it can be optimised and easy to retrieve all the data for as many rows added to TableLayout on the AddMore Button click.
How to retrieve values and set ids for Row Components.
EDIT ::
Modification of code as suggested by #Rohit Heera
I have written following code:
projectTableLayout = (TableLayout) rootView.findViewById(R.id.projectsTableLayout);
projectTableLayout.setStretchAllColumns(true);
yearAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_dropdown_item, Constants.YEAR_ARRAY);
projectTypeAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_dropdown_item, Constants.PROJECT_TYPE_ARRAY);
projectListData = new ArrayList<ProjectData>();
for(int i = 0; i < 5 ; i++)
{
tableRowStartCount = i;
TableRow projectItemRow = new TableRow(getActivity().getApplicationContext());
LayoutInflater inflator = (LayoutInflater) getActivity().getSystemService(getActivity().getApplicationContext().LAYOUT_INFLATER_SERVICE);
projectItemRow.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.MATCH_PARENT, 1.0f));
View projectRowView = inflator.inflate(R.layout.project_row_item,projectItemRow,false);
projectNameET = (EditText) projectRowView.findViewById(R.id.project_name__ET);
yearSpinner = (Spinner) projectRowView.findViewById(R.id.yearSpinner);
yearSpinner.setAdapter(yearAdapter);
projectTypeSpinner = (Spinner) projectRowView.findViewById(R.id.projectTypeSpinner);
projectTypeSpinner.setAdapter(projectTypeAdapter);
projectItemRow.addView(projectRowView);
ProjectData projectObj = new ProjectData();
projectListData.add(projectObj);
projectTableLayout.addView(projectItemRow,tableRowStartCount);
}
Can you please let me know how can i implement the eventlistener in the above loop?
Use this code to add rows in table
/**
* this method add the dynamic table row and display the list .
*/
public void displayList(List<Data> datalist) {
int i = 0;
TableLayout projectsTableLayout = (TableLayout) findViewById(R.id.projectsTableLayout);
projectsTableLayout.removeAllViews();
for (i = 0; i <= datalist.size(); i++) {
TableRow singleTableRow = new TableRow(this);
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflator.inflate(R.layout.addattendeelistdata, null);
RelativeLayout parentRelativeLayout = (RelativeLayout) view
.findViewById(R.id.comleteRL);
EditText project_name__ET = (EditText) view
.findViewById(R.id.project_name__ET);
Spinner yearSpinner = (Spinner) view
.findViewById(R.id.yearSpinner);
Spinner projectTypeSpinner = (Spinner) view
.findViewById(R.id.projectTypeSpinner);
singleTableRow.addView(view);
/** Add row to TableLayout. */
projectsTableLayout.addView(singleTableRow, i);
}
}
And for get Reference for each object you need to Create seperate class .
If you tell me on which event you can move to next class so i can help you better.
Thanks
Like Edit Text you need to create separte class for spinner item listeners and store the value and main list automatically get all the new values.
/**
* this method add the dynamic table row and display the list .
*/
List<ProjectData> mainList=new List<ProjectData>();
// calling function
displayList(mainList);
public void displayList(List<ProjectData> datalist) {
int i = 0;
TableLayout projectsTableLayout = (TableLayout) findViewById(R.id.projectsTableLayout);
projectsTableLayout.removeAllViews();
for (Iterator<ProjectData> it :datalist.hasNext();) {
TableRow singleTableRow = new TableRow(this);
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflator.inflate(R.layout.addattendeelistdata, null);
RelativeLayout parentRelativeLayout = (RelativeLayout) view
.findViewById(R.id.comleteRL);
EditText project_name__ET = (EditText) view
.findViewById(R.id.project_name__ET);
Spinner yearSpinner = (Spinner) view
.findViewById(R.id.yearSpinner);
Spinner projectTypeSpinner = (Spinner) view
.findViewById(R.id.projectTypeSpinner);
project_name__ET.addTextChangedListener(new ListenEditText(it.next()) );
singleTableRow.addView(view);
/** Add row to TableLayout. */
projectsTableLayout.addView(singleTableRow, i);
}
}
class ListenEditText implements TextWatcher
{
ProjectData data;
ListenEditText(ProjectData data)
{
this.data=data;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
data.project_name=s.toString();
}}
ModelClass;
class ProjectData
{
public String project_name;
public String year;
public String projectType;
}

Inflate layout and use its child items

I have a layout where I want to imitate a listview by adding items programmatically one below the other. So I created an .xml for the layout of these items that are something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_lista"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginTop="5dp"
android:layout_toLeftOf="#+id/rellay_btn"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:text="Some name"
android:textColor="#3F3F3F"
android:textSize="17sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_tip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/iv_follow"
android:text="Some text"
android:textColor="#3F3F3F"
android:textSize="13sp" />
</LinearLayout>
In the activity I would like to generate n of this layout, fill the textviews with text and also I would like to set an onClickListener on them. n is the size of an array. Please help
Note: Once the activity loads, the number of layouts will not change, nor can a layout be removed.
This is what I have now but the layout is displayed on top of the activity instead of below a Textview:
LayoutInflater inflater = LayoutInflater.from(BucketProfileActivity.this);
for (int i = 0; i < 3; i++) {
View view = inflater.inflate(R.layout.bucketprofile_tips, null);
view.setId(i);
TextView tv_username = (TextView) view.findViewById(R.id.tv_username);
tv_username.setText(String.valueOf(i));
RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
rl.addRule(RelativeLayout.BELOW, R.id.tv_nemkell);
addContentView(view, rl);
}
If your posted xml file is bucketprofile_tips.xml then you need to change here from
TextView tv_username = (TextView) view.findViewById(R.id.tv_title);
to
TextView tv_username = (TextView) view.findViewById(R.id.tv_username);
Because in bucketprofile_tips.xml tv_title id not found for your TextView. So you are getting Null Pointer Exception.
Not sure why you would want to do this but you can just use a LayoutInflater to inflate x of this view and add them to a designated ViewGroup. For example:
LayoutInflater inflater = LayoutInflater.from(context);
for (int i = 0; i < numberOfViews; i++) {
View v = inflater.inflate(R.layout.view_to_add, parentView, false);
setup(v);
parentView.addView(v);
}
Where setup() is a function you define that does the setup work such as setting the text of a TextView etc.
For instance, in your setup function might look something like this:
private void setup(View v) {
TextView tv = (TextView) v.findViewById(R.id.name);
// set the text of the text view
tv.setText("Hello!");
// set the click listener for the view...
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do stuff here...
}
});
}
LinearLayout parentLayout=findViewById(R.id.parentLayout);
LayoutInflater inflater = LayoutInflater.from(BucketProfileActivity.this);
View view = inflater.inflate(R.layout.bucketprofile_tips, null);
parentLayout.addView(view);
LinearLayout textList=(LinearLayout) parentLayout.getChildAt(0);
for(int i=0; i<textList.getChildCount(); i++){
TextView tv_username=(TextView) textList.getChildAt(i);
textView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
tv_username.setText(String.valueOf(i));
}
}
}

build layout at runtime android

i have a complex xml layout which has list views..a row in the list view contains several text fields which are spaced evenly. i am using textview to store the text and then finally add all the items to the row...its working perfectly fine.
but now i have case where in i am not sure, how many text fields i might get from a webservice. therefore i need to create the textview dynamically on run time, populate them and then insert into the list..
is there anyway to declare,add and populate new textview fields on runtime?
or is there is anyway to implement the spacing between the two fields?
result of first call
__________________________
|_____|_____|_____|______|
result of second call
________________________________
|_____|_____|_____|______|______|
I tried implementing the solution that was provided below (Kenny), but for some reason I am unable to add views into the list.. below is my code
public class HeaderAdapter extends ArrayAdapter<Header> {
final Header[] listSymbols;
private TextView textView;
private LinearLayout row;
public HeaderAdapter(Context context, int symResourceID,
Header[] objects) {
super(context, symResourceID, objects);
listSymbols = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.header_view, parent, false);
Header headerRec = listSymbols[position];
for(int i = 0 ; i < listSymbols.length;i++){
textView = new TextView(getContext());
textView.setLayoutParams(new LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, //Width of the view
ViewGroup.LayoutParams.WRAP_CONTENT));//Height of the view
textView.setId(i);
row.add??
}
}
The main activity that calls this
setContentView(R.layout.main);
headerList.add(new Header("Symbol","Quantity","Price","Price Yesterday","52 Week High","52 Week Low","Change","Days Gain","Days Gain %","Returns"));
Header[] tmpHeaderList = headerList.toArray(new Header[headerList.size()]);
ArrayAdapter<Header> headerAdapter = new HeaderAdapter(this,R.layout.twoway_header_view,tmpHeaderList);
headerListView.setAdapter(headerAdapter);
xml layout file..the main file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<HorizontalScrollView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:scrollbars="none"
android:id="#+id/headerHv">
<ListView android:id="#+id/header_listView1"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:background="#color/white" android:cacheColorHint="#00000000"
android:smoothScrollbar="true" android:scrollbars="none" />
</HorizontalScrollView>
</LinearLayout>
the file in which the template for the row is defined
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView android:id="#+id/headerList" android:layout_width="80dp"
android:layout_height="wrap_content" android:textColor="#000000"
android:typeface="sans" android:textStyle="normal" />
</LinearLayout>
Here is the way i dynamically generate custom buttons from a list, you could do the same thing with textViews:
//Setup Buttons
layout = (LinearLayout)findViewById(R.id.layoutBars);
int count = lBars.size();
for(int i = 0; i< count;i++){
final Bar b = lBars.get(i);
BarButton button = new BarButton(DDTBars.this, R.drawable.barsmall , b.getName().toUpperCase());
button.setLayoutParams(new LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
button.setId(i);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Run activity passing name of the bar to retrieve data
Intent i = new Intent(DDTBars.this, DDTBar.class);
i.putExtra("name", b.getName());
startActivity(i);
}
});
layout.addView(button);
}
So you could try:
//Setup TextViews
layout = (LinearLayout)findViewById(R.id.mylayout);
int count = myTextList.size();
for(int i = 0; i< count;i++){
TextView txtView = new TextView(this);
txtView.setLayoutParams(new LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, //Width of the view
ViewGroup.LayoutParams.WRAP_CONTENT));//Height of the view
txtView.setId(i);
layout.addView(txtView);
}
You could do it in code. Declare TextView 's in a loop and use RelativeLayout to position them wrt each other.

Categories

Resources