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));
}
}
}
Related
I have a custom adapter for a listview and here is the getView method;
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) JourneyPlannerActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.journey_planner_route_detail, viewGroup, false);
LinearLayout layout = (LinearLayout) rowView.findViewById(R.id.journey_planner_detail_detail_main_id);
JourneyPlannerRoute r = m_Routes.get(i);
String directions = "";
for(int j=0 ; j < r.getRoutes().size() ; j++){
ImageView image = new ImageView(JourneyPlannerActivity.this);
String transportMethod = r.getRoutes().get(j).getMeansOfTransport();
if(transportMethod.equals("Train"))
image.setImageResource(R.drawable.network_rail_logo);
else if(transportMethod.equals("Subway"))
image.setBackgroundResource(R.drawable.roundel_tube);
else if(transportMethod.equals("Bus"))
image.setBackgroundResource(R.drawable.bus);
else if(transportMethod.equals("Walk"))
image.setBackgroundResource(R.drawable.walking);
image.setVisibility(View.VISIBLE);
layout.addView(image);
//directions += r.getRoutes().get(j).getMeansOfTransport()+",";
}
directions += " "+r.getDuration();
TextView tv = (TextView) rowView.findViewById(R.id.journey_planner_detail_main_text_view);
tv.setText(directions);
return rowView;
After going through the debug it seems the imageviews are being added to the layout but they're just not appearing on the screen;
I had a feeling it was due to not picking up the correct layout but it seems as though it is?!
Here is the xml file for the row;
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/journey_planner_detail_detail_main_id">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/bus_small"/>
<TextView
android:id="#+id/journey_planner_detail_main_text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
Instead of creating new Image view just call rowView.findViewById(R.id.image_id); (you'll have to add id to the xml).
The actual bug is with the TextView. It is set to fill_parent causing the newly added ImageView to appear to the right of the visible screen. You can change this by changind the TextView width to wrap_content. However, using the ImageView defined in xml layout is better.
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
I have an inflated Linear Layout that contains 2 TextViews inside it.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_m"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/ll_borders"
android:tag="m"
android:text="m" />
<TextView
android:id="#+id/tv_q"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/ll_borders"
android:tag="q"
android:text="q" />
</LinearLayout>
All i want is that when this Linear Layout is inflated then i want to get the only TEXTVIEW on which i click. For example if i click on "tv_m" then it shall only return me the text of tv_m.
May b its simple but i am not getting a way to it. So i need help.
Thanks
After inflating the layout get the textview objects as below
LinearLayout layout = inflater.inflate(<your layout name>, null);
TextView textView1 = layout.findViewById(R.id.tv_m));
TextView textView2 = layout.findViewById(R.id.tv_q));
String selectedText;
textView1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedText = textView1.getText().toString();
}
});
Similarly you can put listener for textView2 also. The selectedText will be the final string which you want.
You need to set up on click listeners for the text views. Then when one is clicked, it will call a function in your code passing it the view that was touched. Then you can call getText on it.
here is the code just check this out :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout lt = (LinearLayout) findViewById( R.id.linearLayout );
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(your xml to be inflate, null, false);
lt.addView(view);
TextView tv_m = (TextView)view.findViewById( R.id.tv_m);
TextView tv_l = (TextView)view.findViewById( R.id.tv_l);
tv_m.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv_m.getText(); // to get the value written on text view
} });
}
I add a ListView on runtime like this:
MainMenue = getResources().getStringArray(R.array.Unit);
// remove all controls
LinearLayout formLayout = (LinearLayout)findViewById(R.id.submenue);
formLayout.removeAllViews();
menueview = new ListView(getApplicationContext());
menueview.setVisibility(ListView.VISIBLE);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
menueview.setLayoutParams(params);
menueview.setAdapter(new submenueadapter(menueview.getContext(), MainMenue));
// Set the on Item
SetMenueOnClick() ;
formLayout.addView(menueview);
and then I add a item click listener like this:
public void SetMenueOnClick() {
menueview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final String text = (String) ((TextView)view).getText();
}
});
}
But then I have an error:
06-03 10:59:25.862: E/AndroidRuntime(14732): at android.view.ViewRoot.handleMessage(ViewRoot.java:2109)
android.widget.LinearLayout cannot be cast to android.widget.TextView
at this line:
final String text = (String) ((TextView)view).getText();
Any idea how to get the text in this issue? the adapter looks like this:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.shortmenue, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.contents);
textView.setText(values[position]);
// Change icon based on name
String s = values[position];
System.out.println(s);
rowView.setBackgroundResource(R.drawable.alternate_list_color);
return rowView;
}
and R.layout.shortmenue is simple, only a TextView like below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/contents"
android:textSize="34dp"
/>
</LinearLayout>
Your row is a TextView wrapped by a LinearLayout so you might want to do this:
LinearLayout ll = (LinearLayout) view; // get the parent layout view
TextView tv = (TextView) ll.findViewById(R.id.contents); // get the child text view
final String text = tv.getText().toString();
If you are running on a similar problem but you sure you have targeted a linearLayout:
Delete the file gen/your.app.package/R.java.
This happens because of a xml bug, when you delete R.java it will be recreated on the next build/run.
I just added android:id="#+id/my_layout" to LinearLayout that wrapped TextView and that solved similar problem.
I had the same problem and I just renamed inserted view object.
Like this:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/newTextViewName"
android:textSize="34dp"
/>
In my case an XML contained a TextView, but I made a mistake writing
final TextView text = (TextView) inflater.inflate(R.layout.item_text, layout);
instead of
final TextView text = (TextView) inflater.inflate(R.layout.item_text, layout, false);
You can resolve this by replacing
final String text = (String) ((TextView)view).getText();
with
TextView temp= (TextView) view.findViewById(R.id.textView);
This works for me.
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.