Java edittext to xml android - java

I am trying to do a app with multiple EditText and is wondering if there is any easy way to do that.
For instance to add matrix of EditText from your java code to your activity_main.xml or maby do a for loop which adds them at your specified location.
EditText[][] edittext = new EditText[10][10];
gridView = (GridView) findViewById(R.id.gridview);
for (int i=0;i<9;i++){
for (int j=0;j<9;j++){
gridView.addView(edittext[i][j], column X, row Y);
}
}

Here is a working example..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout root = (LinearLayout) findViewById(R.id.master);
EditText t[][] = new EditText[10][10];
LinearLayout.LayoutParams dim = new LinearLayout.LayoutParams(LinearLayout.LayoutParams
.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
for (int i=0;i<9;i++){
for (int j=0;j<9;j++){
t[i][j]=new EditText(this);
t[i][j].setLayoutParams(dim);
t[i][j].setHint("Hello World , EditText[" + i + "]" + "[" + j + "]");
root.addView(t[i][j]);
}
}
}

There is no easier way to make a "form". Each EditText is a different xml component with different id, with its own attributes.
What you can do is an adapter with listview/recyclerview with EditText the holder.

You can do smth like that:
ArrayList<EditText> editTexts = new ArrayList<>();
LinearLayout ll = (LinearLayout) findViewById(R.id.container);
EditText oneOfEditText;
for (int i = 0; i < 100; i++){
oneOfEditText = new EditText(this);
oneOfEditText.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
));
oneOfEditText.setHint("MyHint");
oneOfEditText.setId(i);
ll.addView(oneOfEditText);
editTexts.add(oneOfEditText);
}
And then you can access these EditTexts like that:
for (EditText editText : editTexts){
Log.d("myLog", editText.getText().toString());
}
But the best practice for such things is to create them statically in xml, and then you can access them either via static ids, or like that:
for (int i =0; i < ll.getChildCount(); i++){
editTexts.add((EditText) ll.getChildAt(i));
}

I think the proper way implement each item is to use an adapter. In your case, you can use SimpleAdapter or create a custom adapter that extends BaseAdapter and set it using setAdapter(ListAdapter).
You can check the documentation for GridView here:
http://developer.android.com/guide/topics/ui/layout/gridview.html

Related

Any way to initialize multiple views with similar ID names?

I am using CheckBoxes and faced similar problem while using TextViews, the following method works correctly but is redundant. I did the same while using TextViews which were 10 in number.
private CheckBox []checkBoxes ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_toast);
checkBoxes = new CheckBox[5];
checkBoxes[0] = findViewById(R.id.checkBox1);
checkBoxes[1] = findViewById(R.id.checkBox2);
checkBoxes[2] = findViewById(R.id.checkBox3);
checkBoxes[3] = findViewById(R.id.checkBox4);
checkBoxes[4] = findViewById(R.id.checkBox5);
}
I have given the id's of the checkboxes a general name, is there any function I can use?
I was thinking if there is someway like following:
for(int i=1;i<=5;i++){
checkBoxes[i-1]=findViewById(R.id.checkBox(somehow use i));}
Or is there any TOTAL DIFFERENT approach I can take?
You can do it by declaring an int array in your resources, with the entries being your CheckBox IDs.
Example:
<resources>
<integer-array name="check_box_ids">
<item>#id/checkBox1</item>
<item>#id/checkBox2</item>
<item>#id/checkBox3</item>
<item>#id/checkBox4</item>
</integer-array>
Then, in your onCreate, you'll loop through either your local array or the one you created in your resources (check_box_ids) - make sure they have both the same size!
int[] checkBoxIds = getResources().getIntArray(R.array.check_box_ids);
for (int i = 0; i < checkBoxIds.length; i++) {
checkBoxes[i] = findViewById(checkBoxIds[i]);
}
If you are trying to simplify things:
private int[] ids = {R.id.checkBox1,R.id.checkBox2,R.id.checkBox3,R.id.checkBox4,R.id.checkBox5};
private CheckBox []checkBoxes = new CheckBox[5];
//loop
for(int i =0 ; i<checkBoxes.length ; i++){
checkBoxes[i] = findViewById(ids[i]);
}
UPDATE
This might be helpful
Instead of ids, tag your views:
<LinearLayout
id = "#id/layout"
........
<CheckBox
android:tag = "1"
......
<CheckBox
android:tag = "2"
......
........
in code:
private CheckBox []checkBoxes = new CheckBox[5];
private LinearLayout linearLayout;
//on create
linearLayout = findViewById(R.id.layout);
//loop
for(int i =0 ; i<checkBoxes.length ; i++){
checkBoxes[i] = (CheckBox)linearLayout.findViewWithTag(String.valueOf(i+1));
}

How can I set a view's gravity and layout_gravity programmatically in Java instead of XML?

For my activity, we were tasked with creating the views entirely programmatically (not allowed to use XML).
I created what I want the layout to look like in XML.
but I'm having trouble getting my contentEditText and the gravities to correctly set the, up as I've done in the XML file.
This is what I have for my view.
public class NoteGridLayout extends GridLayout {
public NoteGridLayout(final Context context, EditText titleEditText, Spinner spinner, EditText contentEditText, Button backButton) {
super(context);
setColumnCount(2);
GridLayout.Spec colSpec, rowSpec;
colSpec = GridLayout.spec(0, 1, 1);
rowSpec = GridLayout.spec(0, 0, 0);
GridLayout.LayoutParams titleParams = new GridLayout.LayoutParams(rowSpec, colSpec);
colSpec = GridLayout.spec(1,1,1);
rowSpec = GridLayout.spec(0,0,0);
GridLayout.LayoutParams spinnerParams = new GridLayout.LayoutParams(rowSpec, colSpec);
colSpec = GridLayout.spec(0,2,1);
rowSpec = GridLayout.spec(1,1,1);
GridLayout.LayoutParams contentParams = new GridLayout.LayoutParams(rowSpec, colSpec);
colSpec = GridLayout.spec(0,2,1);
rowSpec = GridLayout.spec(2,1,0);
GridLayout.LayoutParams buttonParams = new GridLayout.LayoutParams(rowSpec, colSpec);
titleParams.width = 0;
titleParams.height = LayoutParams.WRAP_CONTENT;
spinnerParams.width = 0;
spinnerParams.height = LayoutParams.WRAP_CONTENT;
contentParams.width = 0;
contentParams.height = 0;
buttonParams.width = LayoutParams.MATCH_PARENT;
buttonParams.height = LayoutParams.WRAP_CONTENT;
contentParams.setGravity(Gravity.TOP);
titleEditText.setLayoutParams(titleParams);
spinner.setLayoutParams(spinnerParams);
contentEditText.setLayoutParams(contentParams);
backButton.setLayoutParams(buttonParams);
addView(titleEditText);
addView(spinner);
addView(contentEditText);
addView(backButton);
}
}
The two main problems I'm having are:
1. The titleEditText is not appearing to span an entire column, rather, the spinner is taking up the whole two columns.
2. The contentEditText gravity is not able to be set, placing the text at the top of the box.
What do I need to do to fix these two problems?
For layout_gravity following is a code snippet,
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.CENTER;
yourView.setLayoutParams(params);
For Gravity use following line,
yourLayout.setGravity(Gravity.CENTER)

How to edit TextView parameters programmatically?

I'm trying to make a Scheduling app, and in doing so have made a Schedule screen with TextViews and Views that represent the time slots that an activity can correspond to.
However I'm having a hard time getting a generated TextView (which will represent the activity on the Schedule) to line up correctly with the View associated with the Activity's start time.
For example in this case I make a TextView with text = "CSI2120", and attempt to line it up with line (which is a View) above the "13:00" TextView here. However I am missing something as the advice from these links as I can't get them to work.
Can I set “android:layout_below” at runtime, programmatically?
Android How to change layout_below to TextView programmatically (See Second Way in the Answer)
The TextView is in the default location on the top-right, not where I want it to be. What should be doing instead of what the links advise?
Here is my full method. timeSlots is an array of R.id.view[####] ints and Schedule is the Activity the method is in:
public void displayDailyActivities(int[] timeSlots){
String[] todaysActivities = {"CSI2120", "01", "14", "2017", "0300", "0400"};
// Make the associated TextView(s)
for(int i=0; i < todaysActivities.length; i=i+6){
int startTime = Integer.valueOf(todaysActivities[i+4]);
int startTimeHour = startTime / 100;
int startTimeMin = startTime % 100;
// Make the TextView and add it to the Schedule
// Code I got from links
TextView newActivity = new TextView(Schedule.this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// Make the activity, grabbing the corresponding timeslot (View) from the timeSlots array
newActivity.setText(todaysActivities[i]);
// In this case ( timeSlots[startTimeHour + 1] ) returns ( R.id.view0300 )
// which is the View (line) on the Schedule directly above to the "03:00" TextView
relativeParams.addRule(RelativeLayout.BELOW, timeSlots[startTimeHour + 1]);
newActivity.setLayoutParams(relativeParams);
linearParams.setMargins(0, startTimeMin-3, 0, 0);
newActivity.setLayoutParams(linearParams);
// Add to the screen
RelativeLayout schedule = (RelativeLayout) findViewById(R.id.scheduleView);
schedule.addView(newActivity);
// Make sure we're not going out of bounds
if(i + 6 > todaysActivities.length){
i = todaysActivities.length;
}
else{
}
}
}
EDIT: The code that I've found from other similar questions, specifically, that doesn't work for me are the lines:
TextView newActivity = new TextView(Schedule.this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
...
relativeParams.addRule(RelativeLayout.BELOW, timeSlots[startTimeHour + 1]);
newActivity.setLayoutParams(relativeParams);
linearParams.setMargins(0, startTimeMin-3, 0, 0);
newActivity.setLayoutParams(linearParams);
you are overriding the relativeParams with the linearParams. set margins to relativeParms variable iteself and then setLayoutParams to newActivity like below:
relativeParams.addRule(RelativeLayout.BELOW, timeSlots[startTimeHour + 1]);
relativeParams.setMargins(0, startTimeMin-3, 0, 0);
newActivity.setLayoutParams(relativeParams);
// Add to the screen
RelativeLayout schedule = (RelativeLayout) findViewById(R.id.scheduleView);
schedule.addView(newActivity);
This can solve your problem
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(10,10,10,10);
TextView textView = (TextView) findViewById(R.id.textView);
textView.setLayoutParams(params);

Dynamically created TextViews in Java - NullPointerException

I try to add dinamically some TextViews in Java. I assume that when I want to use setText() method, I should earlier connect my Java's TextView object with XML's TextView - I use setId().
At the end, I got NullPointerException in the line where I use setId().
My code:
TextView[] tvQuestion = new TextView[numberOfQuestions];
TextView[] tvAnswer1 = new TextView[numberOfQuestions];
TextView[] tvAnswer2 = new TextView[numberOfQuestions];
TextView[] tvAnswer3 = new TextView[numberOfQuestions];
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
for (int i = 0; i < numberOfQuestions; i++) {
tvQuestion[i].setId(View.generateViewId()); // NullPointerException!
tvAnswer1[i].setId(View.generateViewId());
tvAnswer2[i].setId(View.generateViewId());
tvAnswer3[i].setId(View.generateViewId());
tvQuestion[i].setLayoutParams(params);
tvAnswer1[i].setLayoutParams(params);
tvAnswer2[i].setLayoutParams(params);
tvAnswer3[i].setLayoutParams(params);
tvQuestion[i].setText(question[i]);
tvAnswer1[i].setText(option1[i]);
tvAnswer2[i].setText(option2[i]);
tvAnswer3[i].setText(option3[i]);
layAll.addView(tvQuestion[i]);
layAll.addView(tvAnswer1[i]);
layAll.addView(tvAnswer2[i]);
layAll.addView(tvAnswer3[i]);
}
EDIT:
Solution: Philipp Jahoda's post.
You just created an Array for the TextViews. The TextViews inside the Array are null as long as they are not initialized.
So you need to call
tvQuestion[i] = new TextView(Context);
tvAnswer[i] = new TextView(Context);
// and so on ...
// and then later
tvQuestion[i].setId(View.generateViewId());
// and so on ...
before setting the ID and other stuff.

Custom Android TextView with a border, and create multiple using for-loop?

So, I want to create a custom Android TextView with a border INSIDE AN XML FILE, so not programmatically, and create 10 of those using a for-loop. Something like this:
LinearLayout layout = new LinearLayout(//something, //something);
TextView tv;
String[] data = //Certain data which I'm getting
for(int i = 0; i < data.length; i++) {
tv = (TextView) findViewById(R.id.tvTest);
layout.addView(tv);
}
But this doesn't work for me for some reason. So to summarize:
> Create custom TextView in XML (NOT PROGRAMMATICALLY with Java, but in XML)
> Create an x amount of this particular TextView
> Add it to the screen in Java
Can you help me with this?
This is code snippet
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for ( ) {
View listItemView = inflater.inflate(R.layout.detaillistitem, _ListLayout, false);
_ListLayout.addView(listItemView);
TextView descriptionText = (TextView) listItemView.findViewById(R.id.Text1);
descriptionText.setText("");
}
R.layout.detaillistitem is item u want to inflate.
_ListLayout is LinearLayout to which you can add above item.
Try like this..
Create your textview in an external layout file..
for(int i = 0; i < data.length; i++) {
View v = LayoutInflater.from(this).inflate(R.layout.textview, null);//R.layout.textview is your textview id you want to repeat..
layout.addView(v);
}

Categories

Resources