Any way to initialize multiple views with similar ID names? - java

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));
}

Related

Adding TextViews programmatically

I have found a couple ways to do this, but my issue is that my code has to be a LinearLayout with a horizontal orientation. So what happens is the dynamically created TextViews go off the screen.
The code I have is below:
mProductAttrLayout.setOrientation(LinearLayout.HORIZONTAL);
mProductAttrLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
for (ProductAttribute productAttribute : aProductAttributes) {
String name = productAttribute.getName();
TextView attr = new TextView(getContext());
attr.setText(name);
attr.setPadding(8, 8, 8, 8);
attr.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
attr.setTextColor(getResources().getColor(R.color.black));
mProductAttrLayout.addView(attr);
for (int i = 0; i < productAttribute.getValues().size(); i++) {
TextView value = new TextView(getContext());
value.setText(productAttribute.getValues().get(i));
value.setTextColor(getResources().getColor(R.color.black));
value.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
value.setPadding(8, 8, 8, 8);
mProductAttrLayout.addView(value);
}
}
What I currently have is:
| name: value, value, value, val--|
what I need is something like:
name: value, value(unknown number of values)
but I need it to go the the next line in the screen if it's too wide like below:
| name: value, value, value,---|
| value, value, value. ------------|
Hope you can understand what I need?
LinearLayout is the wrong choice here.
You could either write your own layout or use existing work.
What you probably want is usually called a FlowLayout, like this.
Custom layouts can be used like any other Layout. E.g. you can add views with layout.addView. Noramlly the only difference in use is reflected in the custom layoutParams.
Create a flow layout in OnCreate:-
muscle_gp_tag_flow_layout = new FlowLayout(mContext);
//add the flow layout to your main layout
Call the method first time and whenever you want to refresh the view:-
public void createShowSpannableStringMuscleGroup(List<MuscleGroup> muscleGroups) {
// clears the flowlayout views
muscle_gp_tag_flow_layout.removeAllViews();
for (int countGroup = 0; countGroup < muscleGroups.size(); countGroup++) {
MuscleGroup group = muscleGroups.get(countGroup);
if (group.getName() != null && group.getName().length() > 0) {
// inflating the textview views in flow layout
TextView textView=new textView(context);
//set color, background for textview
textView.setText(group.getName().toString());
// adding views to flowlayout muscle group
muscle_gp_tag_flow_layout.addView(mView);
}
}
You have to go with Creating a Customized LinearLayout class. Refer the link for some sample ideas.
How can I add a TextView to a LinearLayout dynamically in Android?
you can use SpannableStringBuilder and TextAppearanceSpan. Example code:
List<String> manyStrings = Arrays.asList(new String[]{"name", "value", "value", "value"});
TextView textView = (TextView) view.findViewById(R.id.textView);
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
for (int i = 0; i < manyStrings.size(); i++) {
String text;
if (i == 0) {
text = manyStrings.get(i) + ": ";
} else if (i == manyStrings.size() - 1) {
text = manyStrings.get(i);
} else {
text = manyStrings.get(i) + ", ";
}
if (i == 0) {
spannableStringBuilder.append(text);
spannableStringBuilder.setSpan(new TextAppearanceSpan(getActivity(), android.R.style.TextAppearance_DeviceDefault_Large), 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
int oldLength = spannableStringBuilder.length();
spannableStringBuilder.append(text);
spannableStringBuilder.setSpan(new TextAppearanceSpan(getActivity(), android.R.style.TextAppearance_DeviceDefault_Small), oldLength, spannableStringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
textView.setText(spannableStringBuilder);
Read more about SpannableStringBuilder and TextAppearanceSpan:
http://developer.android.com/reference/android/text/SpannableStringBuilder.html
http://developer.android.com/reference/android/text/style/TextAppearanceSpan.html
I know this is an old question I asked long ago but they (Google) have given us a solution to this problem using FlexboxLayout with the flexWrap="wrap" attribute.
This is for anyone else that finds this question with the same problem.
Example in XML:
<com.google.android.flexbox.FlexboxLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flexWrap="wrap" />
For more info you can visit the github repo here FlexboxLayout Repo
It works like this:
Can read more over here:
Build flexible layouts with FlexboxLayout

Java edittext to xml android

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

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.

Android crashes when try to overwrite TextViews

I've created a timetable app, which allows the user to enter data and then view it.However if the user enters an entry, on a day and time where there already is one, my emulator crashes(forces a close).
Basically I'm pulling back data to a linear layout- which contains 10 TextViews, each representing the times 9-15.
Here's the code:
public void addMondayGrid() {
// TODO Auto-generated method stub
for (int index = 0; index < info.mon.size(); index++) {
// int entryId = info.monIds.get(index);
int time = info.monTimes.get(index);
int id = info.monIds.get(index);
int duration = info.monDuration.get(index);
String dayOfWeek = "mon";
timeId = getResources().getIdentifier("mon" + time, "id",
getPackageName());
if (duration == 1) {
SpannableString text = new SpannableString(info.mon.get(index));
setEntryColour(text);
final TextView textV = (TextView) findViewById(timeId);
textV.setTextSize(10);
textV.setText(text, BufferType.SPANNABLE);
textV.setId(id);
deleteGridEntry(textV);
} else {
longerDuration(time, index, id, info.mon, dayOfWeek);
}
}
}
The thing is is works fine as long as there isn't two entries for the same day and time, eg. monday at 9 oclock.
Anyone have any ideas?I'm quite new to this and any help would be much appreciated!
I have to reference the id this way as there are too many ids to reference any other way,is there not a simple way to overwrite the old textView with new data pulled back from the database? I want the id to be the same one as that is the textView I want to deal with, but it just keeps crashing, is it something to do with instances?
change:
final TextView textV = (TextView) findViewById(timeId);
to:
final TextView textV = (TextView) findViewById(R.id.timeId);

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