I have a LinearLayout that is dynamically declared through the Run_Time, though i don't have a fixed names or tags to define that Layout, though i tried to assign a tag to wach Layout depends on some variable and retrieve it by that variable later, like that :
layout.setTag(index , "something"); // "index" is a variable it's value obtained through the run_time
but i got that error :
ERROR/AndroidRuntime(643): Caused by: java.lang.IllegalArgumentException: The key must be an application-specific resource id.
and after search i found that the problem is that i must assign a fixed resource to that tag but then i won't be able to differentiate between the different layout , so is there's a way to reach my approach?
The reason you're not able to use setTag(int, Object) is because android require a pre-compiled unique id in the 'int' argument.
one way is:
declare your tag in String file like follow:
<string name="FirstTag">1</string>
<string name="SecondTag">2</string>
and for setting that use:
layout.setTag(R.string.FirstTag, "something");
and for getting value:
layout.getTag(R.string.FirstTag).toString();
another way is create a new file called values/tags.xml and write:
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<item name="FirstTag" type="id">1</item>
</resources>
OR you can use R.id.* as Tag Id too, i think you can handle your problem with that
Check this out :
(Use Of Tag)
Java Code:
public class DynamicTetView extends Activity
{
RelativeLayout rl1;
Button b1;
TextView txt,txt3;
int i = 0;
HashMap<String, Integer> map = new HashMap<String, Integer>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_tet_view);
rl1 = (RelativeLayout)findViewById(R.id.rl1);
b1 = (Button)findViewById(R.id.button1);
RelativeLayout.LayoutParams param2 = new RelativeLayout.
LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
param2.setMargins(5, 0, 0, 5);
txt3 = new TextView(this);
txt3.setId(500);
Log.d("Id of txt3........", ""+txt3.getId());
txt3.setText("Hii");
rl1.addView(txt3, param2);
for(i=0;i<10;i++)
{
RelativeLayout.LayoutParams param = new RelativeLayout.
LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
param.setMargins(5, 0, 0, 5);
txt = new TextView(this);
txt.setId(i+1);
txt.setTag(i+1);
Log.d("Id........", ""+txt.getId());
map.put("hi"+txt.getId(), i);
if(txt.getId()!=1)
{
param.addRule(RelativeLayout.BELOW,(txt.getId()-1));
}
else
{
param.addRule(RelativeLayout.BELOW,txt3.getId());
}
txt.setText("Text"+(i+1));
rl1.addView(txt,param);
txt.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
String tag = v.getTag().toString();
Toast.makeText(getBaseContext(),"You clicked "+tag, Toast.LENGTH_LONG).show();
}
});
}
b1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
rl1.removeAllViews();
}
});
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DynamicTetView" >
<RelativeLayout
android:id="#+id/rl1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="48dp"
android:text="Clear" />
</RelativeLayout>
</RelativeLayout>
Related
I have a button inside a view that checks some constraints, and then starts another activity, however the startActivity() call does not do anything, the new activity's onCreate() never gets called, and the code then continues past it. I have checked using logging and breakpoints, and the conditions are being met and startActivity() is being called. Both activities are defined in the application manifest.
From the source activity's onCreate():
int[] winning_player;
int next_player;
int[] scores;
[...]
final Button end_turn_button = (Button) findViewById(R.id.end_turn);
end_turn_button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (winning_player[0] == next_player) {
Intent intent = new Intent(getApplicationContext(), FinalScreenActivity.class);
intent.putExtra("SCORES", scores);
startActivity(intent);
}
}
});
FinalScreenActivity.java
public class FinalScreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_screen);
Intent intent = getIntent();
final int[] scores = intent.getIntArrayExtra("SCORES");
// put the scoreboard in ascending order
Arrays.sort(scores);
// find the scoreboard in the view
TableLayout scoreboard = (TableLayout) findViewById(R.id.scoreboard);
// get the string resources to be formatted
Resources res = getResources();
String player_name_format = res.getString(R.string.player);
// Set the scoreboard in the view
Log.d("brains.PlayActivity", "onCreate: Creating scoreboard");
// for each player entry in the scoreboard
for (int i = 0; i < scores.length; i++) {
Log.d("brains.PlayActivity", "onCreate: adding scoreboard entry "+String.valueOf(i));
// create 2 TextViews
TextView player_name = new TextView(FinalScreenActivity.this);
TextView player_score = new TextView(FinalScreenActivity.this);
// Set the size of the TextViews
player_name.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
// set the first one to the player's name string resource
player_name.setText(String.format(player_name_format, i + 1));
// set the second one to the player's score resource, which takes the score twice (once for the number itself, and once to work out which plural is needed)
player_score.setText(res.getQuantityString(R.plurals.brains, scores[i], scores[i]));
// Create a TableRow to put the score into
TableRow scoreboard_entry = new TableRow(FinalScreenActivity.this);
// Set the size of the TableRow
scoreboard_entry.setLayoutParams(new TableRow.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
// Add the TextViews to the TableRow
scoreboard_entry.addView(player_name);
scoreboard_entry.addView(player_score);
// Add the TableRow to the TableLayout
scoreboard.addView(scoreboard_entry);
}
// Get the title text
TextView title_text = (TextView) findViewById(R.id.title_text);
title_text.setText(res.getQuantityString(R.plurals.win_brains, scores[scores.length - 1], scores.length - 1, scores[scores.length - 1]));
// set the play again button
Button play_again_button = (Button) findViewById(R.id.play_again_button);
play_again_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), SelectPlayersActivity.class);
startActivity(intent);
}
});
}
}
and activity_final_screen.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="uk.co.bluesapphiremedia.android.zombiedice.FinalScreenActivity"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/title_text"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="#+id/scoreboard"
android:layout_below="#+id/title_text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/play_again"
android:id="#+id/play_again_button"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
end_turn_button.setOnClickListener(this);
//override onClick() method in activity implement interface View.OnClickListner
public void onClick(View v) {
if(v.getId() == R.id.end_turn){
if (winning_player[0] == next_player) {
Intent intent = new Intent(this,FinalScreenActivity.class);
intent.putExtra("SCORES", scores);
startActivity(intent);
}
}
}
In my project I have some EDITTEXT being generated at runtime , the number of EDITTEXT is variable.
Must recover typed text and store in different variables , and then create a JSON object with it.
Here is the method I use to create the EditText :
public View editText(String nmLabel, String tpRender) {
EditText e = new EditText(getBaseContext());
e.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
// e.setHint("DATE");
if(tpRender.equals("NUMBER")) {
e.setHint("NUMBER");
}
else if(tpRender.equals("DATE")) {
e.setHint("DATE");
}
else if(tpRender.equals("TEXT")) {
e.setHint("TEXT");
}
e.setTextColor(Color.BLACK);
e.setTextSize(20);
return(e);
}
How do I get the text entered separately?
As your EditTexts are created at runtime and you need to get the value from all of them to create your json, you could use a List and store your individual EditTexts there. Something like:
In the xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:id="#+id/layout">
</LinearLayout>
In your activity,
List<EditText> allEditTexts; // The List to hold all EditTexts
LinearLayout layout; // The anchor layout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (LinearLayout) findViewById(R.id.layout);
allEditTexts = new ArrayList<EditText>();
// I am running it three times, you can run as many times as you want
for (int i = 0; i < 3; i++) {
EditText editText = (EditText) editText("ANY LABEL", "NUMBER");
layout.addView(editText);
allEditTexts.add(editText);
}
// Now I am adding a button that will read the values from the List when clicked
Button button = new Button(getApplicationContext());
button.setText("Click");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Read the input here for all EditTexts. Then you can store it in some Array or process it differently. In my code I have just logged them.
for (EditText editText : allEditTexts) {
Log.d("TEXTINPUT", editText.getText().toString());
}
}
});
layout.addView(button);
}
// This is the code that you have, almost untouched.
public View editText(String nmLabel, String tpRender) {
EditText e = new EditText(getBaseContext());
e.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
// e.setHint("DATE");
if (tpRender.equals("NUMBER")) {
e.setHint("NUMBER");
} else if (tpRender.equals("DATE")) {
e.setHint("DATE");
} else if (tpRender.equals("TEXT")) {
e.setHint("TEXT");
}
e.setTextColor(Color.BLACK);
e.setTextSize(20);
allEditTexts.add(e);
return (e);
}
Hope this helps you!
I have created an Android RSS Reader App.I have a text marquee in my android app.Iam fetching RSS feed and store RSS title as an array.Iam setting this array as the marque text.Check the code,
String MarqueeStr="";
TextView flashnews;
for (int i = 0; i < nl.getLength(); i++) {
MarqueeStr = MarqueeStr +" | "+ Headlines.Title[i];
}
flashnews.setText(MarqueeStr);
Now I have to set an onclick listener for my marquee, so that user can view detailed description of title which they are clicked.I know how to set it.But my problem is, how can i get the array index of clicked string in the marquee text when a user click on the marquee?
here is my XML layout,
<TextView
android:id="#+id/flashs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:lines="1"
android:ellipsize="marquee"
android:layout_marginLeft="70dp"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:textColor="#e7e7e7" />
screen shote here..
can you see that "Latest News"? its my marquee text
I think that will only be possible if you will create your textviews dynamically and set id for them. like if you are having 10 news link then use 10 textviews
TextView txt = null;
View.OnClickListener marquee_click = new View.OnClickListener() {
#Override
public void onClick(View v) {
int selected_item = v.getTag();
switch (selected_item) {
case 0:
break;
case 1:
break;
case 2:
break;
default:
break;
}
}
};
LinearLayout news_text_layout = new LinearLayout(getApplicationContext());
news_text_layout.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 0; i < 10; i++) {
txt = new TextView(getApplicationContext());
txt.setTag(i); // OR txt.setId(i);
txt.setText("new " + i);
txt.setOnClickListener(marquee_click);
news_text_layout.addView(txt);
}
// ADD YOUR LINEAR LAYOUT ON WHICH YOU HAVE ADDED ALL TEXT VIEW IN YOUR LISTVIEW FOOTER.
// NOW PERFORM SAME ANIMATION OR TRICK ON LINEAR LAYOUT WHICH YOU WERE PERFORMING ON marquee text.
Hope it can help you...
You can add every FlashNews as a dynamically created TextView. And you can put all of these in
one HorizontalScrollView. And set their listeners seperatly.
For marquee function, you can programmatically scroll the horizontalView within your code.
I dont know if it's possible to make it with your idea. (Actually it can be done, but it will contain pain i guess)
for animation look at this i have just created.
Create new project then add class and xml file which i am giving.
public class Test_stflowActivity extends Activity {
LinearLayout ll = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout1);
final TranslateAnimation ts = new TranslateAnimation(200, -100, 0, 0);
ll.setAnimation(ts);
ts.setDuration(5000);
TextView tv = new TextView(getApplicationContext());
tv.setText("*bharat sharma*");
tv.setTextSize(30);
ll.addView(tv);
ll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ll.startAnimation(ts);
}
});
}
}
this is xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" >
</LinearLayout>
</RelativeLayout>
it is working for me
if you use a ListView with an adapter, (which you should), you can use the getItem(int position) function to get the specific item.
In my soundboard app I have 80 buttons that have a on click listener and a on long click listener.
My buttons are declared in xml as:
<TableRow
android:id="#+id/tableRow1"
android:layout_height="wrap_content" >
<Button
android:id="#+id/sound0"
android:layout_width="1dip"
android:layout_height="fill_parent"
android:layout_weight=".31"
android:longClickable="true"
android:text="#string/sound0" >
</Button>
<Button
android:id="#+id/sound1"
android:layout_width="1dip"
android:layout_height="fill_parent"
android:layout_weight=".31"
android:longClickable="true"
android:text="#string/sound1" >
</Button>
<Button
android:id="#+id/sound2"
android:layout_width="1dip"
android:layout_height="fill_parent"
android:layout_weight=".31"
android:longClickable="true"
android:text="#string/sound2" >
</Button>
</TableRow>
And the listeners are set as:
Button SoundButton0 = (Button) findViewById(R.id.sound0);
SoundButton0.getBackground().setAlpha(150);
SoundButton0.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String name = getString(R.string.sound0);
tracker.trackEvent("Clicks", "Play", name, 0);
playSound(R.raw.sound0);
}
});
SoundButton0.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
String name = getString(R.string.sound0);
tracker.trackEvent("Clicks", "Saved", name, 0);
ring(soundArray[0], name);
return false;
}
});
Is there a way I can do all of this programmatically in a for loop so that the only thing changed for each button is SoundButtonx where x is increased by one for each button.
Yes there is a clear solution:
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);
}
Note: Declare XML layout with buttons having id like sound1, sound2, sound3, sound4....and so on.
A more clear-cut example is here for the same problem => Android – findViewById() in a loop
Yes there is. Inside your for loop, you first declare a Button, and pass its constructor a context. Then you set each button's layout params. Add each button to the parent view (use the addView method on the parent view). Finally, use the setContentView method of the activity and pass the parent as a param.
yes take a look at this
for(int x = 0;x<80;x++)
{
Button btn = new Button(this);
btn.setlayoutParams(new LayoutParams(LayoutParams.wrap_content,LayoutParams.wrap_conmtent);
btn.setId(100 + x);
btn.setOnClickListener(this);
btn.setOnlongClickListener(this);
this.addView(btn);
}
//this will create 80 buttons and setlisteners on them
//in your overrides of onclick and onLongClick identiffy them as
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
if(id == 100 + 1 )
{
//your code
}
I want to give ID to some views (textview ,imageview etc) in a layout that is programmetically created.
So what is the best way to set ID.
You create an ids.xml file and place all your required ids in it as below
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="layout1" />
<item type="id" name="layout2" />
<item type="id" name="layout3" />
</resources>
Now for your dynamically created layouts or views you can use these ids as below
new_layout1.setId(R.id.layout1);
new_view2.setId(R.id.layout2);
new_layout3.setId(R.id.layout3);
I hope it may help you.
Google finally realized the need of generating unique IDs for programmatically created views...
From API level 17 and above, one can use View.generateViewId() like this:
view.setId(View.generateViewId());
For apps targeting API level 16 or lower, use ViewCompat.generateViewId() instead:
view.setId(ViewCompat.generateViewId());
create folder res/values/ids.xmland
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="refresh" type="id"/>
<item name="settings" type="id"/>
</resources>
in Activity class call like this
ImageView refreshImg = new ImageView(activity);
ImageView settingsImg = new ImageView(activity);
refreshImg.setId(R.id.refresh);
settingsImg .setId(R.id.settings);
This wont work:
layout.setId(100);
But, this will:
int id=100;
layout.setId(id);
also, this one too (credit: Aaron Dougherty):
layout.setId(100+1);
For compatibility purposes use: ViewCompat.generateViewId()
If you are putting a group of components repeatedly into a layout programmatically like below:
<LinearLayout>
<ImageView>
<TextView>
<Button>
<ImageView>
<TextView>
<Button>
<ImageView>
<TextView>
<Button>
...
</LinearLayout>
then,you can use for loop and give ids accordingly:
for(int i=0;i<totalGroups;i++)
{
ImageView img;
TextView tv;
Button b;
... // set other properties of above components
img.setId(i);
tv.setId(i);
b.setId(i);
... //handle all events on these components here only
... //add all components to your main layout
}
Or if just one group of component you want to add,you can use any integer number which is large and don't conflict with other component's ids in Resources.It won't be much conflicting.
I went about it in a different way.
Created my own R.id HashMap.
Than used the value for the view.setID() part.
String is the id, Integer its value
Private HashMap<String, Integer> idMap= new HashMap<String, Integer>();
private int getRandomId(){
boolean notInGeneralResourses = false;
boolean foundInIdMap = false;
String packageName = mainActivity.getPackageName();
Random rnd = new Random();
String name ="";
//Repaet loop in case random number already exists
while(true) {
// Step 1 - generate a random id
int generated_id = rnd.nextInt(999999);
// Step 2 - Check R.id
try{
name = mainActivity.getResources().getResourceName(generated_id);
}catch(Exception e){
name = null;
}
notInGeneralResourses = false;
if (name == null || !name.startsWith(packageName)) {
notInGeneralResourses = true;
}else{
notInGeneralResourses = false;
localLog("Found in R.id list.");
}
// Step 3 - Check in id HashMap
if(notInGeneralResourses){
List<Integer> valueList = new ArrayList<Integer>(idMap.values());
foundInIdMap = false;
for (Integer value : valueList) {
if (generated_id == value) {
foundInIdMap = true;
localLog("Found in idMAp.");
}
}
}
// Step 4 - Return ID, or loop again.
if (!foundInIdMap) {
localLog("ID clear for use. "+generated_id);
return generated_id;
}
}
}
and to set:
String idName = "someName";
int generated_R_id = getRandomId();
idMap.put(idName,generated_R_id);
someView.setId(idMap.get(idName));
Now, at any point you can just:
ImageView test = (ImageView)
mainActivity.findViewById(idMap.get("somName"));
and to test it -
test.setImageResource(R.drawable.differentPic);
P.S. I've written it like this for ease of explain.
Obviously it can be written better andmore compact.
Try this code!
This should help give an idea.
activity_prac_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:text="#string/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/display_txt"
android:textStyle="bold"
android:textSize="18sp"
android:textAlignment="center"
android:layout_gravity="center_horizontal"/>
<GridLayout
android:id="#+id/my_grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rowCount="4">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linear_view">
<Button
android:text="#string/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/my_btn"
android:layout_gravity="center_horizontal"/>
<TextView
android:text="#string/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/my_txt"
android:textSize="18sp"
/>
</LinearLayout>
</GridLayout>
</LinearLayout>
here's the rest of code
public class AnotherActivity extends AppCompatActivity {
private int count = 1;
List<Integer> gridArray;
private TextView myDisplayText;
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gridArray = new ArrayList<>();
gridArray.add(Integer.valueOf(1));
setContentView(R.layout.activity_prac_main);
findViews();
}
private void findViews(){
GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid);
gridLayout.setColumnCount(4);
LinearLayout linearLayout = (LinearLayout) gridLayout.findViewById(R.id.linear_view);
linearLayout.setTag("1");
Button myButton = (Button) linearLayout.findViewById(R.id.my_btn);
myButton.setTag("1");
TextView myText = (TextView) linearLayout.findViewById(R.id.my_txt);
myText.setText("1");
myDisplayText = (TextView) findViewById(R.id.display_txt);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView txt = (TextView) view;
myDisplayText.setText("PRESS " + txt.getTag().toString());
if(count < 24) {
createView();
}
else{
dialogBox();
}
}
});
}
private void createView(){
LinearLayout ll = new LinearLayout(this);
ll.setId(Integer.valueOf(R.id.new_view_id));
ll.setTag(String.valueOf(count+1));
Button newBtn = createButton();
newBtn.setId(Integer.valueOf(R.id.new_btn_id));
newBtn.setTag(String.valueOf(count+1));
TextView txtView = createText();
txtView.setId(Integer.valueOf(R.id.new_txt_id));
txtView.setTag(String.valueOf(count+1));
txtView.setText(String.valueOf(count+1));
GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid);
ll.addView(newBtn);
ll.addView(txtView);
ll.setOrientation(LinearLayout.VERTICAL);
gridLayout.addView(ll);
count++;
}
private Button createButton(){
Button myBtn = new Button(this);
myBtn.setText(R.string.button_send);
myBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView txt = (TextView) view;
myDisplayText.setText("PRESS " + txt.getTag().toString());
if(count < 24) {
createView();
}
else{
dialogBox();
}
}
});
return myBtn;
}
public void dialogBox() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GRID IS FULL!");
alertDialogBuilder.setPositiveButton("DELETE",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid);
gridLayout.removeAllViews();
count = 0;
createView();
}
});
alertDialogBuilder.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private TextView createText(){
TextView myTxt = new TextView(this);
myTxt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
return myTxt;
}
}
As you can see ids were created in res -> values -> ids file.
when creating views dynamically id is the same for the views.
Each TextView share same id. Each Button share same id. each layout share same id.
Ids are only important to access the contents of views.
However the Tag is what makes each view unique to each other.
Hope this helps you out!
All you need to do is call ViewCompat.generateViewId()
For Example:
val textView = TextView(this)
textView.text = "Hello World"
textView.setLayoutParams(ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
textView.id = ViewCompat.generateViewId()
You can define your Ids as resources and then use setId() of the view to set it.
In a xml file, define the ID's like:
<resources>
<item type="id">your id name</item>
</resources>
then, use in the java file as..
layout.setId(R.id.<your id name>)