Setting up RelativeLayout in java code - java

I'm having a hard time getting two text views to appear on top of each other in my java code. Here's the code I'm experimenting with:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
layout = new RelativeLayout(this);
text1 = new TextView(this);
text1.setText("1");
text2 = new TextView(this);
text2.setText("2");
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams q = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
q.addRule(RelativeLayout.BELOW, layout.getId());
text1.setLayoutParams(q);
layout.addView(text1);
p.addRule(RelativeLayout.BELOW,text1.getId());
text2.setLayoutParams(p);
layout.addView(text2);
setContentView(layout);
}
This stacks the two text views on the same line, but I want TextView text2, to appear below TextView text1, so in my app I want the following to appear as the output:
1
2
I've tried all sort of things with the "addRule" method, I'm not sure why this isn't working. I want to know how to do this without XML because I plan to build a library of methods that can build up a layout that is easily adjustable through editing an array.

Your TextViews don't have an id (by default the id is -1)... put this after their initialization:
text1.setId(1111); // 1111 is just an example,
text2.setId(2222); // just make sure the id are unique

I don't think you are looking to layout the text1 view below the RelativeLayout since you added all your views to it as children, right? Try removing the first rule; that rule is asking the text view to be below the same view it is in.
EDIT: Also a help is explicitly setting the id of the view you are laying out relative to.
So here:
text1.setId(2);
p.addRule(RelativeLayout.BELOW,2);

you can use xml layout for this :
in relative layout
u set the first textview and assign it some id
fot the next text view we can assign parameter
android:layout_below="id of above text view"
in this way we get 2nd text view below 1st text view

Related

How to dynamically add a widget in android?

I want to add a button widget to a linear layout dynamically but it does not seem to work. In my sum_example.xml file I already have added three widgets in a linear layout that is the root layout.
//Finding the layout
LinearLayout linear = (LinearLayout) findViewById(R.id.sum_example_root);
//Creating a widget
Button button = new Button(this);
//Setting the required parameters of widget
button.setLayoutParams(new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
//Setting optional parameters of widget
button.setId(R.id.added_btn_1);
button.setText("I am added");
button.setTextColor(0x000000);
button.setBackgroundColor(0x00ff00);
button.setOnClickListener(this::sum);
//Adding the widget to the layout
linear.addView(button);
You are on the right track but the Problem is your Colors arguments.
button.setText("I am added");
button.setTextColor(Color.BLACK);
button.setBackgroundColor(Color.MAGENTA);
Try using Color Class Constants instead as I have done above.
//You don't need this
button.setId(R.id.added_btn_1);
Also don't add set an Id on a button since you are not adding it to the View Hierachy. The name identifier should suffice

Android Studio - issue with manipulating Layouts/Views programmatically

I have a few issues with setting LayoutParams and other parameters of my layouts/views programmatically. I cannot specify these in a XML layout file because whether they appear depends on the data held in the database.
The following is a function I use to create a new "Section" which consists of a FrameLayout with its children being View and TextView:
public FrameLayout createSection(long id, String name) {
FrameLayout frame = new FrameLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 100);
params.setMargins(15, 15, 15, 15);
frame.setLayoutParams(params);
View view = new View(this);
LayoutParams viewParams = new LayoutParams(LayoutParams.MATCH_PARENT, 100);
view.setLayoutParams(viewParams);
view.setId(toIntExact(id));
view.setBackgroundResource(R.color.colorButton);
frame.addView(view);
TextView text = new TextView(this);
LayoutParams textParams = new LayoutParams(LayoutParams.MATCH_PARENT, 100);
textParams.setMarginStart(15);
text.setGravity(Gravity.CENTER);
text.setTextAlignment(TextView.TEXT_ALIGNMENT_TEXT_START);
text.setTextColor(getResources().getColor(R.color.colorTextSecondary));
text.setText(name);
frame.addView(text);
return frame;
}
The parent of this newly created FrameLayout is LinearLayout and so based on the other similar questions on StackOverflow I figured setting parameters for FrameLayout should be done through LinearLayout.LayoutParams. However, this does not make a change. The initial XML page contains this:
Initial XML page
The first "SECTION" is created in the XML file, and the other two are created through 'createSection' function. This is the outcome: Design outcome
The issue is that the margins are not set properly and the TextView doesn't seem to care about the Gravity + TextAlignment combination that I'm using.
I would appreciate any help that I could get to resolve this issue.
I apologise for wasting anyone's time. The code seems to work and the margin sizes are different due to these being set in terms of pixels (px) rather than dp as it is in the XML file.
I also forgot to add text.setLayoutParams(textParams); to the TextView object.

Android Text View at run time - Text views inflating as multiple row

How to create multiple text views at run time in multiple rows and column? I have inflated a linear layout and created the text views using for loop. Text Views were created successfully, but i'm facing the issue that all created text views are only in single row. I tried to set it with the LayoutParams also, but cant fixed it. How to fix this? Below is my code
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
appointmentSlotList = appointmentSlot.getAppointmentSlots();
if(appointmentSlotList != null && appointmentSlotList.size()>0){
for(int i = 0; i<appointmentSlotList.size(); i++){
View appointmentInflater = layoutInflater.inflate(R.layout.appointment_time, null);
TextView lblDate = (TextView) appointmentInflater.findViewById(R.id.appointmentTime);
lblDate.setText(appointmentSlotList.get(i));
lblDate.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
//lblDate.setLayoutParams(lparams);
lblDate.setOnClickListener(onclickTime);
try {
//if(previousSelected!=i)
lnrDateContainer.addView(appointmentInflater);
}catch (Exception e){
e.printStackTrace();
}
}
}
and my output is shown below:
Output for the inflated text views shown below the date picker
Set the textview android layout gravity to fill
android:layout_gravity="fill"
If above wont work then refer to this question : Android multi line linearlayout
As you want to add TextView in rows and columns, you can use TableLayout and add TextView in it pragmatically
Check this answer : https://stackoverflow.com/a/16939325/5345482
To achieve these I think FlowLayout library might be fit to your requirements.
With this lib you can create your TextViews in a single line and when doesn't have space then auto inserts the view in the next line.
The link: https://github.com/ApmeM/android-flowlayout
I hope helps you!
Specify the orientation in your Linear Layout as VERTICAL
<LinearLayout
----
android:orientation="vertical"
---- />

Hindi kavita proper alignment/justification

I am developing an app related to hindi kavita(poems). I want the poems to be displayed in the way real poems are displayed like the image shown below
Now the problem is I dont know how to use a textview to show this kind of text
Use a linear layout with vertical orientation. Add a text view for each line, with layout_width="match_parent" and the appropriate gravity attribute.
https://developer.android.com/reference/android/widget/LinearLayout.html
EDIT:
If you have your poem as an arraylist of strings where each element is a line of your poem, you can do:
//Initialise your layout in your activity onCreate()
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout);
layout.setOrientation(LinearLayout.VERTICAL);
//Start listening to your firebase data and put this somewhere in the callback:
// poemLines is a list of Strings you get from firebase
for(i=0; i<poemLines.size(); i++){
TextView view = new TextView(context);
view.setText(poemLines.get(i));
//set any other attributes to your textview that you want, width, height, font, etc
view.setGravity(i%2==0?END:START);
layout.add(view);
}

How to properly set settings for RelativeLayout programatically?

I'm creating a RelativeLayout programatically and I want to place three objects into it: a ListView and two Buttons. I need to set some settings to properly locate them in the window. For now I'm doing it this way:
RekativeLayout rl = new RelativeLayout(context);
rl.setBackgroundColor(Color.WHITE);
rl.setPadding(10, 10, 10, 10);
ListView listView = new ListView(context);
ListViewAdapter adapter = new ListViewAdapter(jParser.getArrayList(), context);
listView.setLayoutParams(new LayoutParams(wWidth, wHeight));
listView.setAdapter(adapter);
RelativeLayout.LayoutParams listParams = new RelativeLayout.LayoutParams(wWidth, wHeight);
listParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
listParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
listView.setId(98515);
listView.setLayoutParams(listParams);
Button moreButton = new Button(context);
moreButton.setLayoutParams(lp);
moreButton.setBackgroundColor(Color.GRAY);
moreButton.setText("More");
RelativeLayout.LayoutParams mButtonParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mButtonParams.addRule(RelativeLayout.ALIGN_LEFT, listView.getId());
mButtonParams.addRule(RelativeLayout.BELOW, listView.getId());
mButtonParams.setMargins(0, 10, 0, 0);
moreButton.setLayoutParams(mButtonParams);
closeButton.setLayoutParams(lp);
closeButton.setBackgroundColor(Color.GRAY);
closeButton.setText("Close");
Button closeButton = new Button(context);
RelativeLayout.LayoutParams cButtonParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
cButtonParams.addRule(RelativeLayout.ALIGN_RIGHT, listView.getId());
cButtonParams.addRule(RelativeLayout.BELOW, listView.getId());
cButtonParams.setMargins(0, 10, 0, 0);
closeButton.setLayoutParams(cButtonParams);
rl.addView(listView);
rl.addView(moreButton);
rl.addView(closeButton);
but I guess this method requires much system resources and isn't acceptable. How should I set the settings properly?
What you are doing is fine, given the question you asked. For the sake of the question I will still answer both.
I think you meant RelativeLayout.LayoutParams. Which let's you set any attributes and customize how the View should behave.
For instance, to create and set the basic height/width:
RelativeLayout myRelativeLayout = new RelativeLayout(this);
myRelativeLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
===========================================================
Now, as far as you other doubts, your real question is if this is optimal and if there are any other ways. (While you should really create another question, I will still answer).
As mentioned in the commments, this is the main reason of xml resources. Here you create your layouts or views and just populate them with data.
Here's a quick guide: http://developer.android.com/guide/topics/ui/declaring-layout.html
A quick breakdown:
-res/layout/ is the directory where your layout xmls will be. (LayoutInflater)
-Inside those you decalre other views (TextView, ImageView, etc).
-You must reference and inflate the resources to be able to call them in code.
-Once inflated you can call findViewById(resourceId) and cast View to the proper Widget (view) type.
Inflating and referencing view items requires a Context. Here's a quick guide to understand how it works:
http://www.doubleencore.com/2013/06/context/
Other references:
You might want to take a deeper look into resources.
Hope this helps, and happy coding!

Categories

Resources