Find TextView which was created programmatically? - java

How can I find those TextView's another function on same class?
I will use setText(), serBackgroundColor() after create.
This code part is on CreateDesign() and this func calling onCreate():
public class MainActivity extends AppCompatActivity {
private LinearLayout linearLayout;
private TextView textView;
public void CreateDesign(){
linearLayout = (LinearLayout) findById(R.id.linearLayout);
for(int i = 1; i <= 5; i++){
textView = new TextView(this);
textView.setId(i);
textView.setText(i + ". TextView");
linearLayout.addView(textView);
}
}

Well you don't necessarily need to use id here, There are several ways to achieve this:
1.
TextView textView = (TextView) linearLayout.findViewById(i);
i is what you set before from 1 to 5.
2.
TextView textView = (TextView) linearLayout.getChildAt(i);
i here is the number of set item, for instance i=0 is the first textView you added using addView() method.

Either you create a member variable of this TextView which you can then use inside this class or you can use findViewById() on your LinearLayout.

Use the normal findViewById() method. You're giving the TextViews unique IDs from 1 to 5, so you can find those TextViews by supplying 1-5 to findViewById().
However, you probably shouldn't be doing it this way, and you shouldn't have a global textView variable (it'll only hold a reference to the last-created TextView).
Instead, try using an ArrayList and adding all of your TextViews to it. Then you won't need to give them IDs that don't follow the standards.
public class MainActivity extends AppCompatActivity {
private LinearLayout linearLayout;
private ArrayList<TextView> textViews = new ArrayList<>();
public void CreateDesign(){
linearLayout = (LinearLayout) findById(R.id.linearLayout);
for(int i = 1; i <= 5; i++) {
TextView textView = new TextView(this);
textView.setText(i + ". TextView");
linearLayout.addView(textView);
textViews.add(textView); //add it to the ArrayList
}
}
}

Related

How to change text of Text View outside of onCreate()

I am trying to change the text of a TextView on my Activity. It happens in a method in the same class as the onCreate method. However, it does not work. I've googled it but found nothing.
This is the error I got:
Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference.
This is the Main Activity, where my TextView is located:
private static TextView welcome;
private static TextView counter;
private static int number;
private static SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Shared Preferences getting called to see if the user has set his name
SharedPreferences sharedpreferences = getSharedPreferences("name", Context.MODE_PRIVATE);
//Getting number
this.number = sharedpreferences.getInt("number", 0);
this.sharedPreferences = sharedpreferences;
Boolean continueName = false;
//Checking if name is set
if (!sharedpreferences.getBoolean("nameSet", false)) {
//If name is not set
Intent intent = new Intent(this, Name.class);
startActivity(intent);
} else {
//if name was already set, default activity pops Up
continueName = true;
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting counter and setting it
TextView count = (TextView) findViewById(R.id.txtNumber);
this.counter = count;
//Actionlistener to +1 Button
ActionListeners al = new ActionListeners();
Button plusOne = (Button) findViewById(R.id.btnAddOne);
plusOne.setOnClickListener(al.getPlusOneListener());
//Setting Text View Object
this.welcome = (TextView) findViewById(R.id.welcomeUser);
//If the name is set
if (continueName) {
this.welcome.setText(getString(R.string.welcome) + " " + sharedpreferences.getString("usersName", ""));
}
}
public void setNameNew() throws InterruptedException {
TextView welcomeThis = this.welcome;
new Thread(new Runnable() {
public void run() {
//Setting welcome text
SharedPreferences sp = getSharedPreferences("name", Context.MODE_PRIVATE);
welcomeThis.setText(getString(R.string.welcome) + " " + sp.getString("usersName", ""));
}
});
Thread.sleep(500);
this.welcome.setText(welcomeThis.getText());
}
public void changeViewNumber(int number) {
//Setting new number
this.counter.setText(number);
}
}
Weird is, that the setNameNew method is working and can change the text of the TextField. But the changeViewNumber method is not working.
Im on the activity where the TextView is located. I can't figure it out. May you please help me?
You can call setText for a TextView anywhere in the class as long as the TextView is referenced. When you say one function is working and the other isn't, it's because the reference for the counter is incorrect.
Your counter reference
TextView count = (TextView) findViewById(R.id.txtNumber);
this.counter = count;
Your welcome reference
this.welcome = (TextView) findViewById(R.id.welcomeUser);
You should be referencing the view the way you referenced welcome. You'll want to change the counter reference to the following.
this.counter = (TextView)findViewById(R.id.txtNumber)
Your count variable does nothing and should be removed.
I would also like to make additional notes for your code. You are using the keyword this, it isn't necessary for your code.
The this keyword refers to the current object in a method or constructor.
The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter.
I would also strongly recommend not putting the main thread to sleep, if the thread is sleeping and action is required it will cause your app to crash.
This is useless
TextView count = (TextView) findViewById(R.id.txtNumber);
this.counter = count;
Just do
counter = findViewById(R.id.txtNumber);
This is because you've declared welcome variable globally in class and initialized in onCreate but you forget to initialize counter on the OnCreate method which is why it is throwing a null pointer exception.
this.counter = (TextView) findViewById(R.id.txtNumber);
just initialize your counter variable just like you did on your welcome variable.
The problem was, that I tried to set the text of a TextView with an Integer
The fix was:
String numberString = Integer.toString(number);
counter.setText(numberString);

Get clicked TextView in ScrollView/LinearLayout?

I have in my program a scroll view with a linearlayout inside of it. I add dynamically TextView's to the linearlayout and I have no way to know how much TextView's I'll end up with. When a certain TextView is clicked I need to get it's text. Any idea what is the best way to do it?
Thanks in advance.
I've tried to add a listener to the text view but I am not sure how to get the text. I saw in some posts that you can do a listener to the LinearLayour/ScrollView though I am not sure what is the best option.
This happenes every time a message is added:
TextView messageText = new TextView(RecordedMessagesScreen.this);
messageText.setText(content);
messageText.setClickable(true);
messageText.setOnClickListener(RecordedMessagesScreen.this.textViewListener);
RecordedMessagesScreen.this.messagesLayout.addView(messageText);
this is the listener:
this.textViewListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra("message", ***NEED TO GET THE TEXT***)
}
};
At the class level declare a String variable:
private String text = "";
and a View.OnClickListener variable:
private View.OnClickListener listener;
Initialize the listener in onCreate() of your activity like this:
listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v;
text = tv.getText().toString();
}
};
and every time you create a new TextView set the listener:
textView.setOnClickListener(listener);
This way the variable text each time you click a TextView will get the clicked TextView's text.
You can customize the code inside onClick() yo suit your needs.

how to display output in textview using android?

i am newbie in android and i m not getting how to produce this output:
Discipline name:1
{ complete for loop code execute from 0 to 9
}
then it will come outside and will update textview text:ie
Discipline name:2
and will enter inside For Loop
{
complete for loop code execute from 0 to 9
}
here is the java code:
public class SummaryDetailActivity extends Activity
{ TableLayout summaryDetailDisciplineTableLayout;
LayoutInflater mInflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.summarydetail_view);
mInflater = getLayoutInflater();
summaryDetailDisciplineTableLayout = (TableLayout)findViewById(R.id.summaryDetail_disciplinetable);
//PLEASE SEE THESE LINE OF CODE:
for(int i=0;i<2;i++)
{
TextView disciplineTextView = (TextView)findViewById(R.id.summaryDetail_disciplinetext);
disciplineTextView.setText("discipline name: "+i);
for(int j=0;j<10;j++)
{TableRow disciplineRow = (TableRow) mInflater.inflate(R.layout.summarydetailrow_view,null);
TextView disciplineDeviceLabel = (TextView) disciplineRow.findViewById(R.id.summaryDetail_info1);
TextView disciplineQuantityLabel = (TextView)disciplineRow.findViewById(R.id.summaryDetail_hypen);
TextView disciplineLocationLabel = (TextView) disciplineRow.findViewById(R.id.summaryDetail_info2);
disciplineDeviceLabel.setText("device no." + j);
disciplineQuantityLabel.setText("quantity No." + j);
disciplineLocationLabel.setText("Location No." + j);
disciplineRow.setId(j);
summaryDetailDisciplineTableLayout.addView(disciplineRow);
}
}
}
}
this code is producing this output:
Why your code is not working the way you want. Is because this
TextView disciplineTextView = (TextView)findViewById(R.id.summaryDetail_disciplinetext);
is initiate as static view that can't be clone in your loop. That's why the value
of the discipline name is 1 not 0. The loop only update the value not clone the view.
You should do this
TextView disciplineTextView = new Textview(this);
disciplineTextView.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
disciplineTextView.setText("discipline name: "+i);
summaryDetailDisciplineTableLayout.addView(disciplineTextView);
for(int j=0;j<10;j++) {
-your code-
}
You should change the xml structure for better UI.
Hope this helps.
Here's how I would've done it.
Inside my XML code, I would create a LinearLayout and within that, a TableLayout.
After fetching the id of my TableLayout, I would dynamically create TableRows and TextViews. You can set their layouts using TableRow.LayoutParams or LayoutParams. You can simply set the text after that and just add them onto the TableRow that you add to TableLayout.
Hope this suggestion helps !
I think that in onCreate() you should use inflater first and then set the view that you have just inflated.
Try this:
View view = getLayoutInflater().inflate(R.layout.summarydetail_view, null);
setContentView(view);

Checking and changing TextView text color

I have ScroolView and it's inside Linear layout. In this linear layout i added programmically around 20 TextView. When i press any of those TextView i change it color to RED (at first it was white). When i press again the same TextView i check his color and if it's is RED i again make it white.
What i want to do:
I press for example 1 TextView and make it RED. Then when i press 2 TextView i make this one RED and i want to make 1 TextView WHITE. This functionality should be at all TextView.
So any idea's how to do this ?
You mean to say at a time you need only one textview to be red. You can do this using 2 variables. One is a boolean colored. This indicates that at least one TextView is colored. Another is a TextView variable. Create a TextView variable lastColoredTextView. Let it be null initially. Then whenever the textview is clicked, assign the lastColoredTextView to the clicked TextView. Then whenever you are clicking, just check if colored then change the color of lastColoredTextView to white.
Change class name and it will work fine.
public class Test_stflowActivity extends Activity {
TextView current_red_txt_box = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = null;
LinearLayout lp = new LinearLayout(getApplicationContext());
lp.setOrientation(LinearLayout.VERTICAL);
View.OnClickListener txt_click = new View.OnClickListener() {
#Override
public void onClick(View v) {
current_red_txt_box.setTextColor(Color.WHITE);
TextView tv = (TextView) v;
tv.setTextColor(Color.RED);
current_red_txt_box = tv;
}
};
for (int i = 0; i < 20; i++) {
tv = new TextView(getApplicationContext());
tv.setId(i);
tv.setTextSize(40);
tv.setText("you text");
tv.setTextColor(Color.WHITE);
tv.setOnClickListener(txt_click);
lp.addView(tv);
current_red_txt_box = tv;
}
setContentView(lp);
}
}

How to repeat textview?

In my Activity I have to add 10 times the same TextView.
Is it possible to load the definition of textview from layout.xml and repeat it programmatically?
for(int i=0;i<10;i++){
Textview text = new TextView(this);
mainlayout.add(text);
}
public class YourClassName extends Activity
{
#Override
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
// set activity layout
setContentView(R.layout.some_activity_layout);
LinearLayout mainActivityLayout = (LinearLayout)findViewById(R.id.main_layout);
LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// then see previous answer
// loop n times {
TextView yourTextView = _li.inflate(R.layout.text_view_layout, null);
mainActivityLayout.addView(yourTextView);
// } end loop
}
}
You may want to read this article on reusing UI components: http://developer.android.com/resources/articles/layout-tricks-reuse.html

Categories

Resources