Search Textview which is created programmatic - android

I'm adding TextViews programmatic using a for-loop and use setId(Int int) to set unique id for that perticular Textview.
But now I want to search textView on the basis of that id.
How can I search?
erorr occurd 'app stopped unexpectedly...' Here is my code.
public class Idtest extends Activity {
TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout ll=new LinearLayout(this);
tv=new TextView(this);
tv.setText("Hello");
ll.addView(tv);
tv=new TextView(this);
tv=(TextView)ll.getChildAt(1);
setContentView(tv);
}
}

tv is obviously null at the end (the LinearLayout only has one child, which is at index 0), so you're basically calling setContentView(null) which results in an exception. It's not clear for me what you're trying to do (your code is pretty messed up).
Supposing you are trying to show multiple TextViews in a LinearLayout, here's my suggestion:
public class Idtest extends Activity {
LinearLayout mainLayout;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainLayout = new LinearLayout(this);
setContentView(mainLayout);
for (int i=0; i < 10; i++) {
TextView tv = new TextView(this);
tv.setText("Hello " + i);
mainLayout.addView(tv);
}
}
}
If, at any later point, you need one of the TextViews, do:
TextView tvX = mainLayout.getChildAt(X); // where X is between 0 and 9
Also, please note that creating layout from code is evil. If you can avoid it, please do. For example, if the number of TextViews is dynamic, then it's perfectly normal to create them from code (although you could inflate them). However, it's not advisable to also create the LinearLayout from code. You should have that in an XML. If it's possible for you to also have the TextViews in an XML, that would be even better.

There is another option too...we have setTag() and getTag() methods. While adding a textview give a tag for it and whenever u want to do a search use getTag().

I suppose you are adding your TextView controls to some ViewGroup (e.g. LInearLayout)?
You can iterate through the ViewGroup child views using getChildCount() / getChildAt(index) and compare the child view id with the one you're searching for.

Related

Use addView instead of a listView

I'm trying to implement a code where there are multiple items.
I am able to populate the ListView and display all these items but I want to inflate a view onItemClick. Unfortunately, AdapterView does not support addView().
So now I want to use addView() to dynamically add items by traversing an ArrayList<>().
How do I do it?
Basically, I want to display a Custom Keypad layout next to a TextView inside the ListView and update the Value of the TextView
This is what I'm trying to do now.
public class OrderSummary extends Activity {
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_summary);
linearLayout = new LinearLayout(this);
View view = View.inflate(this, R.layout.top_bar_layout, null);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
linearLayout.addView(view, params);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(OrderSummary.this, "Clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
What you can do is take a LinearLayout(with orientation set to vertical) instead of a ListView. Then make a custom view for each row, traverse the ArrayList, and then inflate the views and keep adding them to the LinearLayout with addView().
P.S. without the actual code , I cannot tell you how to correct your code.
In your code there is issue where are you adding linearLayout into main container ?

inflates 2 views using same xml:second view contains properties of first view

When changing the text of TextView of the first view, the textView's text of the second view shows the text of both TextViews, one on top of the other.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FrameLayout rl=(FrameLayout) findViewById(R.id.mainLayout);
View v1=LayoutInflater.from(this).inflate(R.layout.text_view, null);
View v2=LayoutInflater.from(this).inflate(R.layout.text_view, null);
TextView myTextView1= (TextView) v1.findViewById(R.id.myTextView);
TextView myTextView2= (TextView) v2.findViewById(R.id.myTextView);
myTextView1.setText("str1");
myTextView2.setText("str2");
rl.addView(v1);
rl.addView(v2);
}
I would guess the issue is because you are using a framelayout so the subviews will overlap. If you switch that framelayout to a linearlayout for example I imagine the results will be as you expect according to the textviews.
very simple.. 1. you have to use append property rather than settext in second textview
2nd you can use extras to pass using intent or use getter setter method like
public static void setstr_name(String str_name) {
GlobalVariable.str_name = str_name;
}
public static String getstr_name() {
return str_name;
}

linking my java layout object with xml layout in android

I have created an LinearLayout object in my .java file and tried to connect it with my .xml layout by using the following code,but it is not responding. Can you please explain to me why and what errors are in this code? I have named the id of the LinearLayout of .xml file as "root".
public class MainActivity extends Activity {
LinearLayout l;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView HelloWorldImageView = new ImageView(this);
TextView t=new TextView(this);
t.setText("hello");
HelloWorldImageView.setImageResource(R.drawable.ic_launcher);
l=new LinearLayout(this);
l=(LinearLayout)findViewById(R.id.root);
l.addView(t);
l.addView(HelloWorldImageView);
setContentView(l);
}
}
Do it like this-
setContentView(R.layout.yourxml);
ImageView HelloWorldImageView = new ImageView(this);
TextView t=new TextView(this);
t.setText("hello");
HelloWorldImageView.setImageResource(R.drawable.ic_launcher);
l=(LinearLayout)findViewById(R.id.root);
l.addView(t);
l.addView(HelloWorldImageView);
You have to set that xml file in the setContentView() which has the root linear layout in it.
First off- you don't need the new LinearLayout line. The findViewById() will return an instantiated version. Same for the the other newed Views.
Secondly- you want to do a setContentView() before making any calls to findViewById(). This way you set the layout (by passing it a layout id), Android will instantiate all the Views in your layout, and you can get references to them via findViewById().

findViewById in specific layout?

Instead of prefixing id's in xml, is it possible to specify the particular layout in code? For example, if I have 3 layouts, each with a button that has an id of "btn". Is it possible to specify which layout to findViewById(R.id.btn) in?
The basic context is defined via setContentView(R.lyaout.my_layout). If you inflate another layout using LayoutInflater.inflate() you get a layout object, lets call it buttonLayout. You can now differ between this.findViewById(R.id.button) and buttonLayout.findViewById(R.id.button) and both will give you different button references.
findViewById is a method of the View class. You can specify where the view should be searched for like that
final View container = new View(context);
container.findViewById(R.id.btn);
If your content view is a complex hierarchy that has several views with id btn, you will need to navigate to a subtree of the hierarchy and search from there. Suppose you have three LinearLayout views, each with a btn view somewhere in it. If you can first select the correct LinearLayout (by id, tag, position, or some other means), you can then find the correct btn view. If the relevant LinearLayout has id of branch1, for instance:
View parent = findViewById(R.id.branch1); // Activity method
View btn = parent.findViewById(R.id.btn); // View method
if you have your btns inside different Viewgroups, it is possible, but requires to give ViewGroups a different name! Easyiest will be for that purpose to define the Layout of the Button inside its own XML (i.e button_layout.xml)
inside your Activity you can do this:
public MyActivity extends Activity{
Button btn1, btn2, btn3;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
LinearLayout ll = new LinearLayout(this);
setContentView(ll);
btn1 = (Button)inflater.inflate(R.layout.button_layout, ll);
btn2 = (Button)inflater.inflate(R.layout.button_layout, ll);
btn3 = (Button)inflater.inflate(R.layout.button_layout, ll);
}
}

Add an array of buttons to a GridView in an Android application

I have an application that will have 5-15 buttons depending on what is available from a backend. How do I define the proper GridView layout files to include an array of buttons that will each have different text and other attributes? Each button will essentially add an item to a cart, so the onClick code will be the same except for the item it adds to the cart.
How can I define an array so I can add a variable number of buttons, but still reference each of them by a unique ID? I've seen examples of the arrays.xml, but they have created an array of strings that are pre-set. I need a way to create an object and not have the text defined in the layout or arrays xml file.
Update - Added info about adding to a GridView
I want to add this to a GridView, so calling the [addView method](http://developer.android.com/reference/android/widget/AdapterView.html#addView(android.view.View,%20int) results in an UnsupportedOperationException. I can do the following:
ImageButton b2 = new ImageButton(getApplicationContext());
b2.setBackgroundResource(R.drawable.img_3);
android.widget.LinearLayout container = (android.widget.LinearLayout) findViewById(R.id.lay);
container.addView(b2);
but that doesn't layout the buttons in a grid like I would like. Can this be done in a GridView?
In the following code, you should change the upper limits of the for to a variable.
public class MainActivity
extends Activity
implements View.OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TableLayout layout = new TableLayout (this);
layout.setLayoutParams( new TableLayout.LayoutParams(4,5) );
layout.setPadding(1,1,1,1);
for (int f=0; f<=13; f++) {
TableRow tr = new TableRow(this);
for (int c=0; c<=9; c++) {
Button b = new Button (this);
b.setText(""+f+c);
b.setTextSize(10.0f);
b.setTextColor(Color.rgb( 100, 200, 200));
b.setOnClickListener(this);
tr.addView(b, 30,30);
} // for
layout.addView(tr);
} // for
super.setContentView(layout);
} // ()
public void onClick(View view) {
((Button) view).setText("*");
((Button) view).setEnabled(false);
}
} // class
Here's a nice sample for you:
https://developer.android.com/guide/topics/ui/layout/gridview.html
You should just create buttons instead of imageviews in getView adapter method.
If you are using a GridView, or a ListView (etc), and are producing Views to populate them via the adapter getView(pos, convertView, viewGroup), you might encounter confusion (i did once).
If you decide to re-use the convertView parameter, you must reset everything inside of it. It is an old view being passed to you by the framework, in order to save the cost of inflating the layout. It is almost never associated with the position it was in the layout before.
class GridAdapter extends BaseAdapter // assigned to your GridView
{
public View getView(int position, View convertView, ViewGroup arg2) {
View view;
if (convertView==null)
{
view = getLayoutInflater().inflate(R.layout.gd_grid_cell, null);
}
else
{
// reusing this view saves inflate cost
// but you really have to restore everything within it to the state you want
view = convertView;
}
return view;
}
// other methods omitted (e.g. getCount, etc)
}
I think this represents one of those Android things where the concept is a little difficult to grasp at first, until you realize there's a significant optimization available within it (have to be nice to CPU on a little mobile device)

Categories

Resources