Programmatically add an ImageView to Layout - java

I'm trying to add a bunch of ImageView on my UI using a loop, the problem is that I have no Idea if the ImageView is being added or not because when I run the app it just gives me a blank white screen.
for(int i = 0; i < jsonArray.length(); i++) {
Log.d("test", "ok"); //the loop works btw
poster.setId(i);
JSONObject jsonObject = jsonArray.getJSONObject(i);
ImageView poster = new ImageView(getApplicationContext());
poster.setBackgroundResource(R.drawable.myPoster);
RelativeLayout.LayoutParams posterParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
posterParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
posterParams.addRule(RelativeLayout.CENTER_VERTICAL);
posterParams.width = 160; //is this DP?
posterParams.height = 220;
relativeLayout.addView(poster, posterParams);
}
Any suggestion is welcome.
EDIT
I added another piece of code just to test if a widget will be added without using a loop:
//test
LinearLayout layout = new LinearLayout(this);
Button btn = new Button(this);
btn.setText("this is a button");
btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
layout.addView(btn);
And I still get the same result, just blank.

First of all, you are giving exactly the same parameter to each ImageView this causes all your ImageView lays on Like STACK only the last one will be visible to you. You may use ScrollView to see if the ImageViews actually added to your root layout
Secondly, set layout parameters to your dynamic ImageViews not your root layout.
Update
How to use ScrollView,
First of all, your XML should contain ScollView and a child (LinearLayout in our case but you can choose any layout depending on your use case) for placing your ImageView
<ScrollView>
<LinearLayout
android:id = "imageViewPlaceHolder">
</LinearLayout>
</ScrollView>
Secondly, in your Java code, you should find an inner layout to add views as follows
LinearLayout placeHolder = findViewById(R.id.imageViewPlaceHolder);
Then you are ready to add ImageViews into placeHolder since your placeHolder wrapped with ScrollView it will create a scroll dynamically if the content height goes beyond the dedicated height.
placeHolder.addView(yourImageView);
Adding everything from Java
HorizontalScrollView hsv = new HorizontalScrollView(context);
hsv.setLayoutParams(yourLayoutParams);
LinearLayout myPlaceHolder = new LinearLayout(context);
myPlaceHolder.setLayoutParams(yourLayoutParamsForLinearLayout);
myPlaceHolder.addView(yourDesiredImageView);
hsv.addView(myPlaceHolder);
yourRootLayout.addView(hsv);
Hope it makes sense, feel free to ask any clarification

try this:
listView = (ListView) findViewById(R.id.lv_info);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, text);
listView.addHeaderView(creatHeader(getString(R.string.abuot_email),getResources().getString(R.string.email_info)));
listView.addHeaderView(creatHeader(getString(R.string.about_phone),getResources().getString(R.string.admin_phone_num)));
listView.addHeaderView(creatHeader(getString(R.string.about_copyright), getResources().getString(R.string.copyright_info)));
listView.addHeaderView(creatHeader(getString(R.string.about_version),getResources().getString(R.string.version_info)));
listView.setAdapter(adapter);
Method creatHeader:
public View creatHeader(String title, String text) {
View v = getLayoutInflater().inflate(R.layout.lv_item_header_info, null);
((TextView) v.findViewById(R.id.tvTitle)).setText(title);
((TextView) v.findViewById(R.id.tvText)).setText(text);
return v;
}
Layout file for items:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/activity_vertical_margin">
<TextView
android:id="#+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ssss"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"/>
<TextView
android:id="#+id/tvText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sssssssss"
android:gravity="center_vertical"/>
</LinearLayout>

Related

How to make Android EditText force its container to scroll

I have an Android app which can create multiple lines each of which contains two spinners and an EditText. If the content gets too wide for the EditText, it breaks into multiple lines and this messes up my layout. So I call setMaxLines(1). But now the EditText scrolls internally. I want the EditText to expand horizontally to fit its content and the containing HorizontalScrollView to scroll. How can I do this?
I tried putting a HorizontalScrollView in a ScrollView and vice versa. Neither way round works. I expected that setting (both) LayoutParams to wrap_content would work but it doesn't.
I haven't included all of the code because it is a big app. Here is the layout XML:-
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- This is an invisible view to request the focus when an EditText gets deleted
in order to stop Android highlighting something else.
It would be nicer to go back into touch mode,
but Android does not provide a way of doing that. -->
<TextView
android:layout_width="1dp"
android:layout_height="1dp"
android:text=""
android:alpha="0"
android:id="#+id/defineinvisible"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/defineclasslayout">
</LinearLayout>
</LinearLayout>
</ScrollView>
</HorizontalScrollView>
The lines containing the EditTexts are added dynamically because the number of them can vary as the app runs.
The code to add a line looks a bit like this (I've left out some irrelevant detail):-
public class OrItem extends LinearLayout implements TextWatcher {
public OrItem(Context context) {
m_nameSelector = new Spinner(m_context);
m_contSelector = new Spinner(m_context);
m_matchString = new EditText(m_context);
m_matchString.setHorizontallyScrolling(false); m_matchString.setMaxLines(1);
m_matchString.setInputType(TYPE_CLASS_TEXT);
}
public setup(...) {
ViewGroup.LayoutParams ww = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
setOrientation(LinearLayout.HORIZONTAL);
addView(m_nameSelector, ww);
addView(m_contSelector, ww);
m_matchString.setText(sa[2]);
m_wasEmpty = sa[2].isEmpty();
m_matchString.addTextChangedListener(this);
addView(m_matchString, ww);
}
}
The OrItem is added under a hierarchy of LinearLayouts that hangs from defineclasslayout.
I tried inserting
but this goes back to line wrapping inside the EditText.
I found workaround for this. I make each individual line a HorizontalScrollView. Then I can scroll a long line. This is less elegant than scrolling the whole view, but it works.
public class OrItem extends HorizontalScrollView implements TextWatcher {
public OrItem(Context context) {
m_layout = new LinearLayout(context);
m_nameSelector = new Spinner(context);
m_contSelector = new Spinner(context);
m_matchString = new EditText(context);
m_matchString.setMaxLines(1);
m_matchString.setInputType(TYPE_CLASS_TEXT);
m_matchString.setHorizontallyScrolling(false);
}
public boolean setup(...) {
ViewGroup.LayoutParams ww = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
addView(m_layout);
m_layout.setOrientation(LinearLayout.HORIZONTAL);
m_layout.addView(m_nameSelector, ww);
m_layout.addView(m_contSelector, ww);
m_matchString.addTextChangedListener(this);
m_layout.addView(m_matchString, ww);
}

Android textView.setText() throws exception

I'm trying to create an app where I can put several times the same kind of layout in a LinearLayout.
The layout just has a TextView and i'm trying to use setText but this line of code doesn't seems to work.
I don't know how many layout I must add to the LinearLayout because it depends of how many drones (I have one layout/drone) the user will have upload to the app, so I made a function that read the text to put in the TextView from a SharedPreference and that also read the number of drones (so the number of layouts) in another SharedPreferences.
The TextView i'im putting the string in is from a layout named dronelayoutmain.
I tried sending just "test" in the setText, but it crashes anyway, so I think that android just can't find my TextView, but I don't really know why.
So here is the function I call in OnCreate that is supposed to add one layout for each drone I have
public void affichagedrone(){
LinearLayout mlineairelayout = (LinearLayout)
findViewById(R.id.lineaireLayout);
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Context mContext;
mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
SharedPreferences droneprefs = mContext.getSharedPreferences("dronepref", MODE_PRIVATE);
SharedPreferences applimaindata = mContext.getSharedPreferences("applimaindata", MODE_PRIVATE);
int nbdrone = applimaindata.getInt(String.valueOf(emplacementNbDrone),1);
String string;
TextView textViewnomConstructeurDrone;
if (nbdrone !=0) {
for(int i=0;i<nbdrone;i++) {
textViewnomConstructeurDrone = (TextView) findViewById(R.id.textViewNomConstructeur);
string = droneprefs.getString(String.valueOf(i),"Fail");
textViewnomConstructeurDrone.setText(string);
final View rowView = inflater.inflate(R.layout.dronelayoutmain, null);
// Add the new row before the add field button.
mlineairelayout.addView(rowView);
}
}
}
And here is the layout i'm trying to put in the LinearLayout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="120dp"
>
<TextView
android:id="#+id/textViewNomConstructeur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="#string/adddrone"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
The function is supposed to check in applimaindata the number of layout to add, and then, in the for(), is supposed to set the Text of the TextView from the droneprefs file and then add the Layout to the main LinearLayout
If this TextView belongs in the newly inflated layout, you must find it after the layout is inflated:
for(int i = 0; i < nbdrone; i++) {
final View rowView = inflater.inflate(R.layout.dronelayoutmain, null);
textViewnomConstructeurDrone = rowView.findViewById(R.id.textViewNomConstructeur);
string = droneprefs.getString(String.valueOf(i),"Fail");
textViewnomConstructeurDrone.setText(string);
mlineairelayout.addView(rowView);
}

Inflate TextViews to LinearLayout

I want to inflate TextViews to LinearLayout.
I have a layout activity_play_game and java class PlayGameActivity.
Currently, for hardcoded number of TextViews it looks like this:
Now I tried to add number of TextViews according to the value of variable numberForbiddenWords. I added a piece of code that looks like this:
LinearLayout playGame = (LinearLayout) findViewById(R.id.activity_play_game);
TextView temp;
TextView[] textViews = new TextView[numberForbiddenWords];
for(int i = 0; i < numberForbiddenWords; i++) {
temp = new TextView(this);
playGame.addView(temp);
textViews[i] = temp;
}
And I have a method that adds textViews to the activity_play_game. Unfortunately now it looks like this:
As you can see it added TextViews at the bottom. So I removed all TextViews from activity_play_game and added LinearLayout to inflate TextViews:
How can I inflate TextViews to this LinearLayout above the buttons?
I found that kind of solution:
activity_to_add_words:
<?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:orientation="vertical">
<TextView
android:id="#+id/textout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
In the java class:
final View addView;
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
addView = layoutInflater.inflate(R.layout.activity_to_add_words,
null);
final TextView textOut = (TextView) addView.findViewById(R.id.textout);
but this is for a View, not TextView. Do you know how to do it?
Get reference of your LinearLayout container_blue and add TextView's to it.
Try this:
LinearLayout playGame = (LinearLayout) findViewById(R.id.container_blue);
TextView temp;
TextView[] textViews = new TextView[numberForbiddenWords];
for(int i = 0; i < numberForbiddenWords; i++) {
temp = new TextView(this);
temp.setText("TextView " + String.valueOf(i));
temp.setId(i);
temp.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
playGame.addView(temp);
textViews[i] = temp;
}
make one layout file using textview like this :
layout_textview.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/txt_spin"
android:textSize="18sp"
android:background="#fff"
android:padding="5dp"
android:textColor="#000"
android:layout_height="wrap_content"/>
then apply following code in your java file:
LinearLayout playGame = (LinearLayout) findViewById(R.id.container_blue);
LayoutInflater li =(LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = li.inflate(R.layout.layout_textview, null);
TextView txt= (TextView) view.findViewById(R.id.txt_spin);
playGame.addView(view);
Hope it works for you...happy coding..:)
As far as I see your initial problem was about adding the items dynamically before the three buttons. If you want to add them before the three buttons simply call playGame.addView(temp,0); This will always add the item to the first position in the layout.
If you need a specific order of the added views you need to play with the for loop to add them in the right order.

Align TextView above EditText

I want to align a TextView above an EditText. The following code is working well when the TextView is not higher than the space between the Top Margin of the window (red line) and the EditText (green line), like in the screenshot.
The problem occurs when the TextView has more lines than in the screenshot: it just "overruns" the EditText, but I want to keep the EditText in foreground.
In other words: I would like to place the TextView's bottom margin onto the green line and let it grow towards the red line, in order to maintain the visibility of the EditText.
// LINEAR LAYOUT
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);
// TEXTVIEW
// how to set bottom margins programmatically?
layout.addView(tv);
// EDITTEXT
// place the EditText to the bottom of the layout, working well
et.setGravity(Gravity.BOTTOM);
et.setInputType(InputType.TYPE_CLASS_TEXT);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.BOTTOM;
et.setLayoutParams(params);
layout.addView(et);
This should do it for you:
// LINEAR LAYOUT
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);
// TEXTVIEW
LinearLayout.LayoutParams paramstv = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,1f);
tv.setLayoutParams(paramstv);
layout.addView(tv);
// EDITTEXT
et.setGravity(Gravity.BOTTOM);
et.setInputType(InputType.TYPE_CLASS_TEXT);
LinearLayout.LayoutParams etparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,8f);
etparams.gravity = Gravity.BOTTOM;
et.setLayoutParams(etparams);
layout.addView(et);
I guess the key is really to wrap both the EditText and TextView into LayoutParams. Probably you have to adjust the weights.
If this one doesn't work, try to create your layout with an XML file (the handling there is easier).
Try using the relative layout instead and set the edittext at the parent's bottom..
In case you don't want to switch to relative layout then try declaring edit text before the text view..
You can set the property of EditText type to textMultiline.
As you're using LinearLayout , set weight for your views
LinearLayout.LayoutParams paramTextView = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 1.0f);
tv.setlayoutParams(paramTextView);
LinearLayout.LayoutParams paramEditText = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 3.0f);
et.setlayoutParams(paramEditText);
This shall give you the result you expect
This below xml code can solve your problem...
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent">
<SrollView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_above="#+id/edittext_id"
android:layout_margin="7dp">
<TextView
android:id="#+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</SrollView>
<EditText
android:id="#+id/edittext_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>

How do i convert this to XML layout format?

This is the code comming from the Activity file. I would like to have the layout looks the same but i want that code in XML format. Because it's so damn disturbing to have some code in dynamically and some in XML files. So please can someone make this from dynamically to xml layout?
protected void initLayout() {
// root view - GRN
LinearLayout rootView = new LinearLayout(this.getApplicationContext());
rootView.setOrientation(LinearLayout.VERTICAL);
this.mText = new TextView(this.getApplicationContext());
this.mText.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
rootView.addView(this.mText);
this.eventLayout = new LinearLayout(this.getApplicationContext());
this.eventLayout.setOrientation(LinearLayout.VERTICAL);
ScrollView sv_obj = new ScrollView(this.getApplicationContext());
sv_obj.addView(this.eventLayout);
rootView.addView(sv_obj);
this.setContentView(rootView);
}
<LinearLayout android:orientation="vertical>
<TextView android:width="wrap_content android:height="wrap_content/>
<ScrollView>
<LinerLayout android:orientation="vertical>
</LinearLayout>
</ScrollView>
</LinearLayout>

Categories

Resources