Android add editText proggramatically onClick - android

so I know the onClick part is quite useless, but just in case it does change anything, ive put it there. so ive got the onClick, and I would like it to add the editText to the current activity, which is called activity_calculation.
I currently have this code which I got from another question :
public void addCalc(View view){
EditText myEditText = new EditText(context); // Pass it an Activity or Context
myEditText.setLayoutParams(new LinearLayoutCompat.LayoutParams(MATCH_PARENT,WRAP_CONTENT)); // Pass two args; must be LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, or an integer pixel value.
activity_calculation.addView(myEditText);
}
any help would be appreciated. maybe you can see what ive done wrong

First get a reference to the activity's root layout. To do this add an id attribute to your activity layout file's root layout. eg :
<LinearLayout
android:id="+id/rootLayout" />
Then, get a reference to it and add the created EditText.
//If your root layout is a RelativeLayout, use that instead
LinearLayout rootView = (LinearLayout) findViewById(R.id.rootLayout);
EditText myEditText = new EditText(rootView.getContext());
myEditText.setLayoutParams(new LinearLayoutCompat.LayoutParams(MATCH_PARENT,WRAP_CONTENT));
rootView.addView(myEditText);

Related

How to use Preference.setLayoutResource() using object

I am attempting to set a Preference layout in code using setLayoutResource() . But this method requires an int id. I have a preset RelativeLayout that I want to pass as an argument, but I get an error saying Preference cannot be applied to RelativeLayout. I suspect it is because I am not passing an R.layout.id. I need this to work because I will addPreferences dynamically using instances of the same layout with different attribute setting. How can I make this work? Thank you. Sample code below.
rLay=(RelativeLayout)View.inflate(Context,R.layout.account_item, null);
nameView =(TextView) rLay.findViewById(R.id.account_name);
numberView =(TextView) rLay.findViewById(R.id.number_name);
pView = new Preference(Context);
pView.setLayoutResource(rLay); ///ERROR HAPPENS HERE///
If you use same layout with dynamically-changing data,
you can create AwesomePreference extends Preference,
then override onBindView(View) to changing TextView's text or something like that.
This is working like ListView's adapter#getView().
Also don't forget to call Preference#notifyChanged() if you changed bound data.
hope this will help.

How do I duplicate fragments?

My FragmentActivity loops and creates 8 Fragments from the same xml and activity. The fragment has a TextView, by passing parameters to the Fragment, I want to display different text inside each TextView of the Fragments. With this method, I can save creating 139 identical fragments with different texts.
Problem, all 8 fragment's TextView changes when I setText(), because they all share the same template (xml and activity).
Solution - see my answer below.
Extremis
It's because when you duplicate your Fragment, you refer to the same view for each fragment you create. You have to change the id of the fragment. If you don't do that you call the same fragment all the time.
Final Answer : On onCreateView method
private static int id = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout mLinearLayout = new LinearLayout(this);
TextView mTextView = new TextView(this);
mTexTView.setId(Id);
id++;
mLinearLayout.addView(mTextView);
return mLinearLayout;
}
After you can use the id of your textview and set the text.
Okay, so I've learned that something was wrong in my code when I tried to duplicate fragments in th way attempted above.
My Solution
I created a new dummy Android project and selected the Navigation type as Scrollable Tabs + Swipe.
I then learned that it had 1 activity:
main.java - whcih extends:
FragmentActivity
and, 2 layout's:
main.xml - which contained:
<android.support.v4.view.ViewPager> , and
<android.support.v4.view.PagerTitleStrip>
Fragment.xml - which contained:
TextView
By adjusting the adapter, I was able to create unique Fragments based on the Same layout (xml).
So ultimately - Create a new dummy project with the Scrollable Tabs + Swipe and adjust your code based on that example.
Hope this help.
Extremis

Change TextView text

I'm trying to change my TextView text from the code.
This is what my xml looks like:
XML:
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal" />
And the code:
TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Hello");
setContentView(tv1);
I'm getting an error on my device and the application stops.
I tried to show a TextView (not connected to an XML TextView) and it worked.
Your approach is incorrect. I think it will be Null Pointer Exception (next time post log cat)
You need to specify the layout you are using first, before finding views.
Java:
// Specify the layout you are using.
setContentView(R.layout.yourlayout);
// Load and use views afterwards
TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Hello");
Kotlin:
// Specify the layout you are using.
setContentView(R.layout.yourlayout)
// Load and use views afterwards
val tv1: TextView = findViewById(R.id.textView1)
tv1.text = "Hello"
Click Here to study exactly you want to know
remove this.. setContentView(tv1);
I got the same problem. My app was stopping too.
Actually, I was writing the code outside of the function/method. So to fix this problem, these lines
TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Hello");
must be inside a function/method. (can be user defined)
(I am new to android studio so I don't know the reason behind the problem but I only know how to fix this. Maybe this helps new ones despite this question being 8 years old.)

android setBackgroundColor in runtime and other general confusion help?

i have a row of buttins created like this
i want to change the background colour at runtime in code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout track1 = (LinearLayout)findViewById(R.id.my_toggle_container);
for (int i = 0; i<32; i++) {
ToggleButton tgl = new ToggleButton(this);
tgl.setId(i);
...
track1.addView(tgl);
this names the id of the togglebuttons 1, 2, 3... (i presume?)
i have an int variable called 'xBtn' that changes 1, 2,..
this is how i get a reference to the button using xBtn
String buttonID = ""+xBtn;
int resID = getResources().getIdentifier(buttonID, "id", "com.thing");
//find the button
ToggleButton tb = (ToggleButton) findViewById(resID);
//change its colour
tb.setBackgroundColor(Color.BLUE);
it crashes on the setBackgroundColor line.
it may be obvious to someone whats wrong and thats what im hoping
any help would be totaly ace ta
thanks
main.xml
<LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:id="#+id/my_toggle_container" android:orientation="vertical">
The id of your togglebuttons is gonna be a number from 1 to 32... However, trying to find the toggle button by id will return null because simply instantiating a new toggle button and giving an id wont help you. findViewById looks in the parent view for a child view with the specified id. If you havent added that toggle button with that id to the view, then findViewById will return null. I am 99.99% sure even without looking at the log, that it crashes because you are calling setBackgroundColor on a null object.
In other words, the id that you set a view to is only relevant once the view is actually added to a parent view. In your case you are probably trying to add these toggle buttons to your main content view, in which case you need grab hold of that view that you used for setContentView and call addView on that view and pass in each new toggle button. Note that this will probably not look right unless you also specify layoutparams for the togglebuttons.
EDIT
If thats your entire main.xml, then you've got other issues. Post the full xml file. In any event, you still are going to have to do what I've said, which is to grab hold of the view or a child view of that view and then add the toggle buttons to it via addView (after giving the togglebuttons their proper ids). Once the button has been added, then you can find it. Note though that if you're gonna add the toggle buttons to a child view of your main view, then you'll likely have to grab hold of that child view and call findViewById on THAT.
For example, you can do a nested call like this. findViewById(1) <--- gets you the LinearLayout or whatever inside of your main content view, then once you have that you can call addView on it. So LinearLayout ll = (LinearLayout)findViewById(someNumber); ll.addView(tb);
Try to use the method setTag() , and then you can get all your ToggleButton by using : findViewByTag();
Perhaps tb is null? Could you check that out?
To expand on what LuxuryMode said... What gets an ID INTO your java is inflating it via setContentView and setting it as content. That's why it's ok to have overlapping (duplicate) IDs in different layouts. You can have #+id/submit_button in layout1.xml and in layout2.xml and the Activity will get you the object via findViewById(R.id.submit_button) based on which one you have loaded into setContentView() at any given moment.
So, we're all guessing that you're probably not setting the content view and hoping that the code will find your object in your non inflated XML, which it won't. Which would lead (as everyone has guessed) to you now dealing with a null object, which you obviously can't set a background color on.
I know it gets confusing cause you have the XML RIGHT THERE!!! But the reality is that the xml isn't "alive". It's just stuff for you to look at until you have tasked the Application with inflating it and converting all of it into Android objects of some kind. A lot of the time this is done mostly transparently to you, so, it's easy to forget that none of these things really exist.
It's very likely that tb is null, because findViewById() didn't go as you expected.
You can verify this by surrounding the erroneous line with try.. catch block:
try {
tb.setBackgroundColor(Color.BLUE);
} catch (Exception e){
}
and watch for the message of e. It's likely to be null pointer exception.
In fact, I think you should not use getResources().getIdentifier(buttonID, "id", "com.thing") in the first place. It seems to me that all these resources are continuously numbered in R file, thus you should simply get the first id (as an integer), and then increment on that.
That is, you should do things like:
// The following code is not tested; I just wrote it here on SO.
for (int resID = R.id.button1; resID <= 32; resID++) {
ToggleButton tb = (ToggleButton) findViewById(resID);
tb.setBackgroundColor(Color.BLUE);
}
this should make all 32 buttons blue.

Designing an Android User Interface: Textview text doesn't change

I'm having issues with understanding how I should organize my user interface in Android. My original plan was to create TextViews and ListViews programatically and change them when buttons are clicked, etc.
Here's my first simple attempt. viewFriends is a method within my Activity class. It's called when a menu button is pressed.
private void viewFriends()
{
mText = new TextView(this);
mText.setText("Gathering information...");
setContentView(mText);
...irrelevant code follows
Why doesn't this seemingly simple example work? How should I logically organize and manage my user interface objects (TextViews, ListViews, Buttons, etc).
Thanks.
The best work would be having those listviews and textviews in your XML files and give them a suitable ID like following:
<ListView
android:id="#+id/myList"
android:layout_width="wrap_content"
android:layout_weight="1"
/>
Just like above have your text view too in XML file an add the android:id attribute.
Once you define this way in your java file have references to them:
ListView myListObj = (ListView)findViewById(R.id.myList);
Now you have an object called myListObj in your java file and now you can do whatever you want to do with it.
:)
Let me if you find any issue in this so that I can update the answer to meet your specific need.
Don`t use setContentView in your method. Usually it should only be called once in the onCreate method of your activity.
Best predefine your bottons/TextViews in xml, get a handle for them (findViewbyId...)
and modify them that way.
If you create them programaticly, just add them to a view containter from your xml.
Like :
setContentView(R.layout.main);
Lets say in main.xml there is a LinearLayout with the id: root.
// get accces to that layout:
LinearLayout rootLayout = (LinearLayout) findViewById (R.id.root);
// create a new TextView
TextView tv1 = new TextView (this);
tv.setText("Hello!");
// add it to your base layout
rootLayout.addView(tv1);
// done! :)
Make a double check on what you are getting in "this".
change it to your java file name.this
You have to reload/refresh your activity once you change it.
Try this
#Override
protected void onResume() {
if(param.equalsIgnoreCase("gr"))
{
finish();
Intent myIntent = new Intent(yourActivity.this, yourActivity.class);
startActivity(myIntent);
}

Categories

Resources