Difference between "findViewById" and "new View(content)" - java

I am trying to create a 3x4 grid of buttons using the following code:
public class Grid extends AppCompatActivity {
LinearLayout myLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_grid);
myLayout = (LinearLayout) findViewById(R.id.content_grid);
for (int i = 0; i < 3; i++) {
LinearLayout row = new LinearLayout(this);
LayoutParams rowParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
row.setLayoutParams(rowParams);
for (int j = 0; j < 4; j++) {
final Button btn = new Button(this);
LayoutParams btnParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
btn.setLayoutParams(btnParams);
btn.setText(" " + (j + 1 + (i * 4)));
btn.setId(j + 1 + (i * 4));
row.addView(btn);
}
myLayout.addView(row);
}
setContentView(myLayout);;
}
}
This code works perfectly fine and creates the grid as I want it, however if I change the line
myLayout = (LinearLayout) findViewById(R.id.content_grid);
to
myLayout = new LinearLayout(this);
Then only the first row of the grid is produced, not the 2nd and 3rd. I want to know why this is happening?
Whether the line
setContentView(R.id.content_grid);
is there or not does not seem make a difference in the second case.
In addition my content_grid.xml file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content_grid"
</LinearLayout>

By default LinearLayout set orientation horizontal. Try set orientation vertical to myLayout by one LayoutParams.

Related

How to wrap dynamically created textviews in android?

I am creating various textviews inside a linear layout (lay). I want that when the textview reach out of the screen then that textview automatically jump on the next line instead of out of the screen. I am a beginner in android and not getting how to achieve it.
Here is my code:
for (int i = 0; i < string.size(); i++) {
final TextView txt = new TextView(con);
txt.setText(string.get(i));
lay.addView(txt);
}
Try This
TextView txt = new TextView(context);
txt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
private void populateViews(LinearLayout linearLayout, ArrayList<TextView> views, View extraView)
{
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float mWidth = displaymetrics.widthPixels;
extraView.measure(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linearLayout.removeAllViews();
int maxWidth = (int) mWidth - extraView.getMeasuredWidth() - 10;
linearLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params;
LinearLayout newLL = new LinearLayout(mContext);
newLL.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
newLL.setGravity(Gravity.LEFT);
newLL.setOrientation(LinearLayout.HORIZONTAL);
int widthSoFar = 0;
for (int i = 0; i < views.size(); i++)
{
LinearLayout LL = new LinearLayout(mContext);
LL.setOrientation(LinearLayout.HORIZONTAL);
LL.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
LL.setLayoutParams(new ListView.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
views.get(i).measure(0, 0);
params = new LinearLayout.LayoutParams(views.get(i).getMeasuredWidth(), LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(10, 2, 10, 2);
LL.addView(views.get(i), params);
LL.measure(0, 0);
widthSoFar += views.get(i).getMeasuredWidth();
if (widthSoFar >= maxWidth)
{
linearLayout.addView(newLL);
newLL = new LinearLayout(mContext);
newLL.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
newLL.setOrientation(LinearLayout.HORIZONTAL);
newLL.setGravity(Gravity.LEFT);
params = new LinearLayout.LayoutParams(LL.getMeasuredWidth(), LL.getMeasuredHeight());
newLL.addView(LL, params);
widthSoFar = LL.getMeasuredWidth();
}
else
{
newLL.addView(LL);
}
}
linearLayout.addView(newLL);
}
This method should be able to help you. I had made this method long back, so with a few modifications you should be able to use it. The first parameter is a LinearLayout which will be the base vertical linear layout which will act as the primary container for the views. The second parameter are the actual views you have to add. The third parameter in my case was an Image which I was using like a placeholder.
You can add like this also.
for (int i = 0; i < string.size(); i++) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = (View) inflater.inflate(
R.layout.Layout_Design, null);
TextView txt = (TextView) view.findViewById(R.id.some_text);
txt.setText("for runtime change");
layout.addView(view);
// layout is linear layout in my case.
}
Layout_Design:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="80dp"
android:layout_height="80dp" >
<RelativeLayout
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="0dp"
android:paddingTop="5dp" >
<TextView
android:id="#+id/some_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SOme Text" />
</RelativeLayout>
</FrameLayout>

why I get java.lang.IllegalStateException: The specified child already has a parent

I had this problem :
java.lang.IllegalStateException: The specified child already has a
parent. You must call removeView() on the child's parent first.
This is my code :
public void fillFormules(List<Category> objectsTextToShow)
{
LinearLayout layoutItemDetail = (LinearLayout) view.findViewById(R.id.layoutItemDetail);
LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.mygallery);
linearLayout.removeAllViews();
for (int j = 0; j <objectsTextToShow.size() ; j++) {
ScrollView scrollView = new ScrollView(getActivity());
scrollView.setBackgroundColor(android.R.color.transparent);
scrollView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
for (int i = 0; i < objectsTextToShow.get(j).getItems().size(); i++) {
LinearLayout separator = new LinearLayout(getActivity());
LayoutParams separatorParams = new LayoutParams(LayoutParams.MATCH_PARENT, 80);
TextView textView = new TextView(getActivity());
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
textView.setBackgroundColor(colorUtils.titleColor);
textView.setLayoutParams(layoutParams);
//textView.setTypeface(FONT_TITLE);
textView.setTextSize(28);
textView.setText(Check.Languages(objectsTextToShow.get(j).getItems().get(i).getName(), LANGUAGE_ID));
separator.setLayoutParams(separatorParams);
linearLayout.addView(separator);
linearLayout.addView(textView);
scrollView.addView(linearLayout);
}
layoutItemDetail.addView(scrollView);
}
// scrollView.addView(linearLayout);
}
The problem is this line
scrollView.addView(linearLayout);
to initialize linearLayout you are using findViewById which implies that linearLayout has already a parent, violating this way the constraint that every view can have only one parent
You can't add any View to another View if the child View already has a parent.
In your situation you should create LinearLayout programmatically, the way you have created your ScrollView
Do this
public void fillFormules(List<Category> objectsTextToShow)
{
LinearLayout layoutItemDetail = (LinearLayout) view.findViewById(R.id.layoutItemDetail);
LinearLayout linearLayout;
for (int j = 0; j <objectsTextToShow.size() ; j++) {
linearLayout = new LinearLayout(getActivity());
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
linearLayout.setOrientation(LinearLayout.HORIZONTAL); // or VERTICAL as per your needs
ScrollView scrollView = new ScrollView(getActivity());
...
...
...
}

Arrange buttons from bottom instead of top?

I am dynamically creating the buttons. But the problem is they are getting created from top. I want to create it from bottom .
public class MainActivity extends Activity implements View.OnClickListener {
int i, j, butNum, lay1num = 1, lay2num = 100, lay3num = 100, store;
Button[] Button;
EditText numBut;
LinearLayout mainLayout;
LinearLayout[] subLayout;
LinearLayout.LayoutParams params;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
butNum = 5;
Button = new Button[butNum];
subLayout = new LinearLayout[3];
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.HORIZONTAL);
mainLayout.setWeightSum(90);
mainLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
layoutGen();
for (j = 0; j < butNum; j++) {
int value = j + 1;
Button[j] = new Button(this);
Button[j].setText("" + value);
Button[j].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Button[j].setTextSize(20);
Button[j].setTag(value);
Button[j].setId(j);
subLayout[0].addView(Button[j]);
Button[j].setOnClickListener(this);
}
mainLayout.addView(subLayout[0], params);
setContentView(mainLayout);
}
Is there anyway I can create buttons which are aligned to the bottom.
subLayout.setGravity(Gravity.BOTTOM);
You nay need to set size of layout to match_parent.
Eventually You may set a layout_gravity like here

add ScrollView and HorizontalScrollView to a TableLayout

my question is like putting a ScrollView HorizontalScrollView and a table containing TextView Array.
This is my main.java:
public class tabla extends Activity {
SitesList sitesList = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabla);
TableLayout layout =(TableLayout)findViewById(R.id.tabla);
TableRow tr[] = new TableRow[80];
TextView variacion[];
TextView nemotecnico[];
TextView precio[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL("http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=75");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
nemotecnico = new TextView[sitesList.getNemotecnico().size()];
variacion = new TextView[sitesList.getVariacion().size()];
precio = new TextView[sitesList.getPrecio().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getRegistro().size(); i++) {
variacion[i] = new TextView(this);
variacion[i].setText(" " +sitesList.getVariacion().get(i));
nemotecnico[i] = new TextView(this);
nemotecnico[i].setText(" " +sitesList.getNemotecnico().get(i));
precio[i] = new TextView(this);
precio[i].setText(" " + sitesList.getPrecio().get(i));
Pattern pattern = Pattern.compile("^([a-z: ]*)?+(\\+?[0-9]+([,\\.][0-9]*)?)$");
Matcher matcher = pattern.matcher(sitesList.getVariacion().get(i));
if (!matcher.matches())
variacion[i].setTextColor(Color.parseColor("#ff0000"));
else
variacion[i].setTextColor(Color.parseColor("#008000"));
}
for (int i = 0; i < 80; i++) {
tr[i] = new TableRow(this);
tr[i].addView(nemotecnico[i], new TableRow.LayoutParams(1));
tr[i].addView(precio[i], new TableRow.LayoutParams(2));
tr[i].addView(variacion[i], new TableRow.LayoutParams(3));
layout.addView(tr[i], new TableLayout.LayoutParams());
}
/** Set the layout view to display */
setContentView(layout);
}
}
As you see in my code:
TableLayout layout =(TableLayout)findViewById(R.id.tabla);
TableRow tr[] = new TableRow[80];
TextView variacion[];
TextView nemotecnico[];
TextView precio[];
And show the TextView in TableRow
for (int i = 0; i < 80; i++) {
tr[i] = new TableRow(this);
tr[i].addView(nemotecnico[i], new TableRow.LayoutParams(1));
tr[i].addView(precio[i], new TableRow.LayoutParams(2));
tr[i].addView(variacion[i], new TableRow.LayoutParams(3));
layout.addView(tr[i], new TableLayout.LayoutParams());
}
/** Set the layout view to display */
setContentView(layout);
But i can't put HorizontalScrollView and ScrollView because my Xml is as shown below.
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/tabla"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/fondo" >
</TableLayout>
Much appreciate your help, thanks!.
I don't understand why you cannot wrap your entire table in both vertical and horizontal scroll views or wrap the individual cells (whichever you prefer). The first option looks like this:
<ScrollView ...>
<HorizontalScrollView ...>
<TableLayout ...>
</HorizontalScrollView>
</ScrollView>
However this only allows the user to scroll horizontally or vertically for each gesture, not diagonally. But this question covers creating a two dimensional ScrollView: Scrollview vertical and horizontal in android.

Scroll TextView to text position

I want to scroll my TextView to make visible a specific position in the text. How can I do that? I tried bringPointIntoView (int offset) but without success.
Source code:
public class TextScrollActivity extends Activity {
public void onCreate (final Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
final int position = 500;
final TextView textView = new TextView (this);
final ScrollView scrollView = new ScrollView (this);
scrollView.addView (textView);
Button button = new Button (this);
button.setText ("Scroll to " + position);
LinearLayout layout = new LinearLayout (this);
layout.setOrientation (LinearLayout.VERTICAL);
layout.addView (scrollView,
new LayoutParams (LayoutParams.FILL_PARENT, 200));
layout.addView (button, new LayoutParams (LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
StringBuilder builder = new StringBuilder ();
for (int i = 0; i < 1000; i++)
builder.append (String.format ("[ %05d ] ", i));
textView.setText (builder);
setContentView (layout);
button.setOnClickListener (new OnClickListener () {
public void onClick (View v) {
System.out.println (textView.bringPointIntoView (position * 10));
// scrollView.scrollTo (0, position * 10); // no
}
});
}
}
For those who have the same problem, I finally made my own implementation of bringPointIntoView:
public static void bringPointIntoView (TextView textView,
ScrollView scrollView, int offset)
{
int line = textView.getLayout ().getLineForOffset (offset);
int y = (int) ((line + 0.5) * textView.getLineHeight ());
scrollView.smoothScrollTo (0, y - scrollView.getHeight () / 2);
}
Don't hesitate if you have a better solution.
Does adding a movement method to the text view solve the problem?
textView.setMovementMethod(new ScrollingMovementMethod());
Just FYI for anyone else with the same problem, on a listView with large listItems, the overloaded bringPointIntoView can be passed a ListView instead of a ScrollView and use the ScrollTo method instead of smoothScrollTo.

Categories

Resources