How can we use a variable in R.id - android

The content of xml are
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/MainFrame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<AbsoluteLayout
android:id="#+id/AbsoluteLayout1"
android:layout_width="match_parent"
android:layout_height="172dp"
android:layout_x="12dp"
android:layout_y="26dp"
android:visibility="invisible" >
</AbsoluteLayout>
<AbsoluteLayout
android:id="#+id/AbsoluteLayout2"
android:layout_width="match_parent"
android:layout_height="172dp"
android:layout_x="20dp"
android:layout_y="184dp" android:visibility="invisible">
</AbsoluteLayout>
</AbsoluteLayout>
Here's the main code
String layoutid;
int ctr = 1;
AbsoluteLayout [] mainlayout = new AbsoluteLayout[12];
while (ctr<3)
{
layoutid = "AbsoluteLayout" + ctr;
mainlayout[ctr] = (AbsoluteLayout)findViewById(R.id.layoutid);
ctr++;
}
We need to make a loop to make
ctr = 1
AbsoluteLayout + ctr = AbsoluteLayout1
ctr++;
AbsoluteLayout + ctr = AbsoluteLayout2
we want to declare the AbsoluteLayout1 and AbsouluteLayout2 but it doesn't work. We know that the R.id.layoutid is the culprit. So how can we resolve it?

I solved it using getIdentifier method
Button[] buttons;
for(int i=0; i<buttons.length; i++) {
{
String buttonID = "sound" + (i+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i] = ((Button) findViewById(resID));
buttons[i].setOnClickListener(this);
}

the id is an intiger value not string:
hope u ll get an idea from below code
while (ctr<3)
{
int layoutid;
if(ctr==1)
{ layoutid = R.id.AbsoluteLayout1;}
else{
layoutid = R.id.AbsoluteLayout2;}
mainlayout[ctr] = (AbsoluteLayout)findViewById(layoutid);
ctr++;
}
---------------------------------------------
all these won post an error as they are handled as int itself manipulate as you want you cant use this as it is as
int[] ctra={R.id.xx,R.id.xxx};
int i=0;
while (ctr<3)
{
mainlayout[i]=(AbsoluteLayout)findViewById(ctra[i]);
i++;}

Related

how to make thumbnail image with initials two char from name android?

I want to thumbnail initials with two word for my image view like "Peter Parker" but am able to get only one word "P"while running code how can get second word after space my code is.
holder.imgName?.text=teamData[position].userImage.substring(0,1)
You can do it functional way:
val peterParker = "Peter Parker"
val initials = peterParker
.split(' ')
.mapNotNull { it.firstOrNull()?.toString() }
.reduce { acc, s -> acc + s }
println(initials) //PP
This would cover cases when a person's name consists of more than 2 words.
I have done some Trick & implemented this avatar with a Button lol ;p
create profile_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="#color/colorWhite"/>
<corners
android:radius="500dp"/>
</shape>
then main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4300313A"
tools:context=".MainActivity">
<Button
android:onClick="clicked"
android:id="#+id/avatar"
android:clickable="false"
android:focusable="false"
android:textColor="#color/colorPrimary"
android:textSize="65sp"
android:focusableInTouchMode="false"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="#drawable/profile_bg"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"/>
<EditText
android:id="#+id/edtname"
android:layout_below="#+id/avatar"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:textSize="18sp"
android:hint="Enter your name"/>
<Button
android:onClick="clicked"
android:textColor="#color/colorBackground"
android:text="Submit Name"
android:textStyle="bold"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/edtname"
android:layout_marginTop="50dp"/>
</RelativeLayout>
then in MainActivity.java (to split the string and get the first letter of each word ~ name in if condition with stringbuilder)
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.edtname);
button = (Button) findViewById(R.id.avatar);
}
public void clicked(View view) {
String str = editText.getText().toString();
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
//First name
if (strArray.length > 0){
builder.append(strArray[0], 0, 1);
}
//Middle name
if (strArray.length > 1){
builder.append(strArray[1], 0, 1);
}
//Surname
if (strArray.length > 2){
builder.append(strArray[2], 0, 1);
}
button.setText(builder.toString());
}
}
Hi you can using following way
String str = "FirstWord SecondWOrd";
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
if (strArray.length > 0)
builder.append(strArray[0], 0, 1);
if (strArray.length > 1)
builder.append(strArray[1], 0, 1);
Log.d("New Text" , builder.toString());
it look's like your using substring to only grab the letters from position 0 to position 1, This is P in Petter
holder.imgName?.text=teamData[position].userImage
.substring(0,1)
If you'd like to grab the words Petter Parker, you have a few options.
• IndexOf & Substring - find the position of a string and get the subtext after.
• Substring - Subtext of string based on parameters
If you plan to change the text length at any stage, you'll need to find the start of the word ( int start = yourString.indexOf("Petter"));
and end of the word ( int end = yourString.indexOf(" "))
IndexOf will return the position of the first letter in your query - Your case it's P in Petter --- So start+"petter".length()
Here's an example of a barcode price checker app I'm working on
// STRING FORMAT 00000899999:0.99
String currentLine = "00000899999:0.99";
int breakPoint = currentLine.indexOf(":");
int end = currentLine.length();
int start = breakPoint + 1;
String Price = currentLine.substring(start,end);
Price will be starting after (:) With +1 or include (:) with no + 1 and end at the lines length.
I wrote an extension function in Kotlin to get initials for a name. You can use a custom view and use draw text and clip shape you want for avatar view.
val initials = "Vikas Patidar".asInitials()
fun String.asInitials(limit: Int = 2): String {
val buffer = StringBuffer()
trim().split(" ").filter {
it.isNotEmpty()
}.joinTo(
buffer = buffer,
limit = limit,
separator = "",
truncated = "",
) { s ->
s.first().uppercase()
}
return buffer.toString()
}

ImageView not updated in ItemList

I am trying to update the image inside ItemList, I am using the below method
This is how I am getting ImageView 'imgView' Object using the below methods -
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(JSONParsingMainActivity.this, contactList,
R.layout.list_item, new String[]{"name", "email", "mobile"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
if(markedQuestion != null){
try {
JSONObject jsonObj = new JSONObject(markedQuestion);
JSONArray contacts = jsonObj.getJSONArray("data");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String questionid = c.getString("questionid");
System.out.println("Question No :" + i + "Question Id is :" + questionid);
Long itemId = lv.getItemIdAtPosition(Integer.parseInt(questionid));
System.out.println("Item Id xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxasdasd" + itemId);
changedView = (CardView) getViewByPosition(Integer.parseInt(questionid),lv);
imgView = (ImageView) changedView.findViewById(R.id.imageViewstickId);
imgView.setImageResource(R.drawable.cancel);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mp.start();
position++;
Intent intent = new Intent(context, DetailsActivity.class);
intent.putExtra("position", Integer.toString(position));
context.startActivity(intent);
}
});
}
public View getViewByPosition(int pos, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition ) {
return listView.getAdapter().getView(pos, null, listView);
} else {
final int childIndex = pos - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
This code is not updating the cancel image in the list item, when I debug I am getting correct id (i.e. 'imageViewstickId' as shown in XML), but the image is not updating, nor giving any error
imgView.setImageResource(R.drawable.cancel);
My XML code also -
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android:id="#+id/cardViewQuestionId"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:cardCornerRadius="15dp"
card_view:cardElevation="2dp"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dp"
android:paddingTop="6dp"
android:text="test"
android:textColor="#color/gradientStart"
android:textSize="16sp"
android:textStyle="bold"
/>
<ImageView
android:id="#+id/imageViewstickId"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center"
/>
</LinearLayout>
<TextView
android:id="#+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#color/gradientStop" />
<TextView
android:id="#+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>
</android.support.v7.widget.CardView>
I have tried everything modifying the code, etc. but nothing works for me
Any help shall be appreciated, thanks
Edits - (Added Debug screen Shot) Please check in debug window, CardViewId is same as XML ImageView id... Still not updating
Solution:
Instead of this:
imgView.setImageResource(R.drawable.cancel);
write:
imgView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.cancel));
Try it. Let's hope it works.
You can simply use this:
If you are in Activity then use this
int id = getResources().getIdentifier("cancel","drawable", getPackageName());
Or in Fragment
int id = context.getResources().getIdentifier("cancel","drawable", context.getPackageName());
// "cancel" drawable resource name
// "drawable" drawable directory
This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following
imgView.setImageResource(id);
hope this will work.
There are two best solutions for that:-
1) Instead of using this
imgView.setImageResource(R.drawable.cancel);
Use This Method:-
imgView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.cancel));
2)Using Glide Library
https://bumptech.github.io/glide/doc/download-setup.html
Your id is correct still it is not updating then it might be a problem that your Resource file (R.java) is not updating try cleaning your project and then check.
If this not works you can also try following code:-
Resources resources = getResources();
imgView.setImageDrawable(resources.getDrawable(R.drawable.cancel));
May be helpful for others to think this way -
I got Clue from this post - how to know when listview is finished loading data on android
My data may be getting updated, but the list was not fully loaded and thats why the data is over writing. I used the following code , thanks for the actual user who posted the above answer
lv.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
Log.d(TAG, "list got updated, do what ever u want");
if(markedQuestion != null){
try {
JSONObject jsonObj = new JSONObject(markedQuestion);
JSONArray contacts = jsonObj.getJSONArray("data");
for (int x = 0; x < contacts.length(); x++) {
JSONObject c = contacts.getJSONObject(x);
String questionid = c.getString("questionid");
System.out.println("Question No :" + x + "Question Id is :" + questionid);
System.out.println(getResources());
changedView = (CardView) getViewByPosition(Integer.parseInt(questionid),lv);
imgView = (ImageView) changedView.findViewById(R.id.imageViewstickId);
// imgView.setImageResource(R.drawable.cancel);
imgView.setImageDrawable(ContextCompat.getDrawable(context,R.drawable.cancel));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});

Android: Dynamically Generated Views added but not shown

I have a UI component with this format:
<RelativeLayout
android:id="#+id/item_lists"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<TextView
android:id="#+id/first_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:text="First List"/>
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/first_list"
android:divider="#android:color/transparent"
android:dividerHeight="10dp" >
</ListView>
</RelativeLayout>
The outer RelativeLayout is the wrapper which I plan to dynamically generate views and inject into, the logic to dynamically add views (a text title and another listview):
private void populateLists() {
View pre = firstList; // this points to the list view "list_view"
if(!titleMap.isEmpty()) { // titleMap is a hashmap that maps titles to lists
Set<String> titles = getTitles();
for(String title : titles){
List<Item> li = titleMap.get(title);
TextView tag = generateTitleTextView(title, pre);
ListView lv = generateListView(li, tag);
sceneLists.addView(tag);
sceneLists.addView(lv);
pre = lv;
}
}
}
generateTitleTextView(String title, View pre) and generateListView(List<Item> list, View pre) are two methods that generate views and place the generated view under View component pre by using
layoutParams.addRule(RelativeLayout.BELOW, pre.getId());
The code can run without exceptions, but the generated views are not visible on the page, I wonder what might be the issue? Thanks in advance!
Edit: The code for generateTitleTextView, generateListView is similar only difference is it generates a ListView
private TextView generateTitleTextView(String title, View pre) {
TextView tag = new TextView(this);
tag.setId(generateRandomViewId());// generates a random int as Id
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
layoutParams.addRule(RelativeLayout.BELOW, pre.getId());
tag.setLayoutParams(layoutParams);
tag.setText(title);
return tag;
}
How do you generate the viewId?
You can use HierarchyViewer or turn on Show layout bounds in Developer Options to debug this.
I think you should try generate view ids with this piece of code:
public static int generateViewId() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
for (; ; ) {
final int result = sNextGeneratedId.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF) {
newValue = 1; // Roll over to 1, not 0.
}
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
} else {
return View.generateViewId();
}
}

How do I get the selected radio button when the radio group is inflated programmatically.

I have a layout that is built dynamically from a database. There are several sections, One of the pieces is a series of radio groups with custom text on each radio button that is read from the database.
My code is properly inflating the layout, adding the correct number of radio buttons and adding the correct text to them.
What I can't figure out is how to get the value of the checked radio button when it is a child of a table row. I am not using an on item selected because I need to wait until the user is sure all the answers are filled in before getting the results. So I have a separate button with an onClick that is going to read the data and store it in the database.
Here is the area in my main XML file
Here is the individual row XML
<RadioGroup
android:id="#+id/radioGroup1"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RadioGroup>
</TableRow>
Here is where I am trying to read the values of the selected radio button
table = (TableLayout) findViewById(R.id.TableLayout03);
for( int ii = 0; ii < nRecs3; ii++ ){
TableRow row1= (TableRow)table.getChildAt(ii);
Log.i("radio button " , " index of row is " + String.valueOf(row1));
View child = table.getChildAt(ii);
int idx = row1.indexOfChild(child);
Log.i("radio button " , " index of child is " + String.valueOf(idx));
RadioGroup radio = (RadioGroup)child;
Log.i("radio button " , " checked button is " + String.valueOf(radio.getCheckedRadioButtonId()));
}
but it's crashing before it gets to the first log statement. I've tried all sorts of variations on getting the value of the child of the child row but nothing is working.
I got it to work. For future reference in case anyone else has this issue you have to have the radiogroup be the child and then work within that to get the buttons.
Here is how I described the table in my main XML file
<ScrollView
android:id="#+id/scroll03"
android:layout_width="fill_parent"
android:layout_height="175dp">
<TableLayout
android:id="#+id/TableLayout03"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TableLayout>
</ScrollView>
Then I have this as the XML file for the row entry:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="#+id/radioGroup1_lbl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:typeface="monospace" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="175dp">
</RadioGroup>
</TableRow>
Here is the subset of code that creates the table rows and radio groups from the database
// Set up the user traits
cmd = String.format("select evaluation_trait_table.trait_name, evaluation_trait_table.id_traitid, " +
"custom_evaluation_name_table.custom_eval_number " +
"from evaluation_trait_table inner join last_eval_table on " +
" evaluation_trait_table.id_traitid = last_eval_table.id_traitid" +
" inner join custom_evaluation_name_table on evaluation_trait_table.id_traitid = " +
" custom_evaluation_name_table.id_traitid where evaluation_trait_table.trait_type = 3 ") ;
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
startManagingCursor(cursor);
nRecs3 = cursor.getCount(); // number of user defined traits to use
dbh.moveToFirstRecord();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
user_evaluation_traits.add(cursor.getString(0));
user_trait_numbers.add(cursor.getInt(1));
user_trait_number_items.add(cursor.getInt(2));
}
inflater = getLayoutInflater();
TableLayout table = (TableLayout) findViewById(R.id.TableLayout03);
for( int ii = 0; ii < nRecs3; ii++ ){
TableRow row = (TableRow)inflater.inflate(R.layout.eval_custom_item, table, false);
tempLabel = user_evaluation_traits.get(ii);
// Set the text for the radiogroup label
((TextView)row.findViewById(R.id.radioGroup1_lbl)).setText(tempLabel);
// Get the text for the buttons
tempText = String.valueOf(user_trait_numbers.get(ii));
cmd = String.format("select custom_evaluation_traits_table.custom_evaluation_item " +
" from custom_evaluation_traits_table " +
" where custom_evaluation_traits_table.id_traitid = '%s' "+
" order by custom_evaluation_traits_table.custom_evaluation_order ASC ", tempText);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
startManagingCursor(cursor);
nRecs4 = cursor.getCount();
dbh.moveToFirstRecord();
ArrayList buttons = new ArrayList();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
buttons.add (cursor.getString(0));
}
radioBtnText = (String[]) buttons.toArray(new String [buttons.size()]);
// Build the radio buttons here
radioGroup = ((RadioGroup) row.findViewById(R.id.radioGroup1));
addRadioButtons(user_trait_number_items.get(ii), radioBtnText);
table.addView(row);
}
Here is the method that creates the radiogroup
private void addRadioButtons(int numButtons, String[] radioBtnText) {
int i;
for(i = 0; i < numButtons; i++){
//instantiate...
RadioButton radioBtn = new RadioButton(this);
//set the values that you would otherwise hardcode in the xml...
radioBtn.setLayoutParams
(new LayoutParams
(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//label the button...
radioBtn.setText(radioBtnText[i]);
Log.i("addradiobuttons", radioBtnText[i]);
radioBtn.setId(i);
//add it to the group.
radioGroup.addView(radioBtn, i);
}
}
And finally the subset of code where I actually read the radio buttons and get ready to update my database
table = (TableLayout) findViewById(R.id.TableLayout03);
if (nRecs3 != 0) {
for( int ii = 0; ii < nRecs3; ii++ ){
TableRow row1= (TableRow)table.getChildAt(ii);
tempTrait = user_trait_numbers.get (ii);
RadioGroup rg=(RadioGroup)findViewById(R.id.radioGroup1);
try {
tempRadioBtn = rg.getCheckedRadioButtonId();
cmd = String.format("select custom_evaluation_traits_table.id_custom_traitid " +
" from custom_evaluation_traits_table " +
" where custom_evaluation_traits_table.id_traitid = %s "+
" and custom_evaluation_traits_table.custom_evaluation_order = %s ", tempTrait, tempRadioBtn+1);
crsr = dbh.exec( cmd );
cursor = ( Cursor ) crsr;
startManagingCursor(cursor);
dbh.moveToFirstRecord();
tempRadioBtn = cursor.getInt(0);
} catch (Exception ex) {
tempRadioBtn = 0;
}
user_scores.add(tempRadioBtn);
}
for( int ii = nRecs3; ii < 5; ii++ ){
user_scores.add(0);
}
}else {
for( int ii = 0; ii < 5; ii++ ){
user_scores.add(0);
}
}
// Fill the user score variables from the user_scores array
trait16_data = user_scores.get(0);
trait17_data = user_scores.get(1);
trait18_data = user_scores.get(2);
trait19_data = user_scores.get(3);
trait20_data = user_scores.get(4);
From there I build my query to do the actual update for this sheep record in the sheep_evaluation_table.
maybe its too late but you can just add setoncheckedlistener. this log id and state. after this you use setter and getter.
hope this will help
private void inflateRadioButton() {
ArrayList arrayList = json_helper_class.getChoice_group_multiple();
for (int i = 0; i < arrayList.size(); i++) {
LinearLayout row = new LinearLayout(Diagnose_Test_Activity.this);
row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
final RadioButton radioButton = new RadioButton(Diagnose_Test_Activity.this);
String a = String.valueOf(arrayList.get(i));
radioButton.setText(a);
radioButton.setId(i);
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String a = String.valueOf(radioButton.getId());
Log.d(TAG, "onCheckedChanged: "+a+b);
//setter here
}
});
row.addView(radioButton);
ll_group_multiple_container.addView(row);
}
}

How to use Android view element by tag

I have some TextView elements in my layout file like below:
<Table Layout>
...
<TableRow android:gravity="center_horizontal">
<TextView
android:id="#+id/tv1"
android:text="#string/text_value"
android:tag="id1">
...
<TableRow android:gravity="center_horizontal">
<TextView
android:id="#+id/tv1"
android:text="#string/text_value"
android:tag="idN">
...
</TableLayout>
I want to use
for (int i=0; i < 10; i++) {
myText = (TextView) findViewbyTag("id"+i);
myText.setText("id is - "+i);
}
construction to match each tag value and set text value into each TextView element.
It doesn't work!
I understand how tp use it by id, but id is int value from resources and I can't
generate it in my for() construction.
What can I do? How do I use findViewbyTag?
You don't need to use tags. You should rather use dynamical resource retrieval as following.
for (int i=0; i < 10; i++) {
// generate id dynamically
int id = getResources().getIdentifier("tv"+i, "id", getPackageName());
// find view by generated id
TextView myText = (TextView) findViewbyId(id);
myText.setText("id is - tv"+i);
}
The both getResources() and getPackageName() are the methods of Context.

Categories

Resources