So I have a simple android app where I take text from a text file (that part is working) and I want to set that text to EditText.setText(). The problem I'm having is that I cannot do this in the onCreate() method because the EditText field and the UI hasn't been created yet(from what it seems).
My question is where would be a good place to do this? Is there a function that is called right after the GUI elements are created?
public class MainActivity extends ActionBarActivity
{
private final String FILE_NAME = "awayReply";
private EditText myEditMessage;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
protected void onStart()
{
String message = readMessage();
myEditMessage = (EditText)findViewById(R.id.edit_message);
if(myEditMessage != null)
{
myEditMessage.setText(message, TextView.BufferType.EDITABLE);
}
}
XML Layout:
<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"
android:orientation="horizontal"
android:paddingBottom="16dp"
android:paddingTop="16dp" >
<EditText
android:id="#+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/lbl_message"
android:inputType="textImeMultiLine" />
<Button
android:id="#+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/edit_message"
android:onClick="updateMessage"
android:text="#string/lbl_update" />
<ToggleButton
android:id="#+id/toggle_away"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/lbl_enable"
android:layout_alignBottom="#+id/lbl_enable"
android:layout_toRightOf="#+id/edit_message"
android:textOff="Disabled"
android:textOn="Enabled"
android:onClick="toggleEnabled" />
</RelativeLayout>
You can't set your text in a TextView until you inflate your layout with
setContentView(R.layout.main_activity);
in the Activity's OnCreate
Once that happens you can do:
EditText editText = (EditText)findViewById(R.id.myEditText)
Full Example:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // this needs to happen first
EditText editText = (EditText)findViewById(R.id.myEditText)
editText.setText("my text", TextView.BufferType.EDITABLE); // <-- needs that second parameter
}
Edit: updated for EditText instead of TextView
I think I figured out my problem. I need to do this work in the PlaceholderFragment where onCreateView is defined. When I call findviewbyid here it dosen't return null.
Related
I am new to java for android.
Then I attempt to put in textview anything, all views do not be shown.
Main.XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="#+id/textNew"
android:text="Hello world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="75px"/>
<Button
android:id="#+id/buttonNew"
android:text="Click me!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity.java:
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
int randomInt;
TextView textNew = findViewById(R.id.textNew);
SharedPreferences sp = getSharedPreferences("settings", Activity.MODE_PRIVATE);
Button clickButton = findViewById(R.id.buttonNew);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textNew.setText("5");
randomInt = Integer.parseInt(sp.getString("setting", "0"));
}
}
I tried to delete textNew.setText("text"). It is helped. But how I can set text!? Me need it!
You can't access the button and the Textview before setting the view content
SetContentView(View) sets the activity content to an explicit view.
In your case, you're setting the view to R.layout.main where the Button and the TextView are defined
To fix this move the onCreate and the setContentView before the rest of the code in the onCreate method
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
I just know how to use Android Studio Code Yesterday. And I got a problem when I need to Change the text when clicking a button.
But when I text, Its don't work.
Here is my code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View bubbleView = getLayoutInflater().inflate(R.layout.bubble_view, null);
Button bubble = (Button) findViewById(R.id.start_bubble);
bubble.setOnClickListener(this);// calling onClick() method
Button predict = (Button) bubbleView.findViewById(R.id.predict);
predict.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.start_bubble:
startService(new Intent(getApplicationContext(), SimpleService.class));
case R.id.predict:
View bubbleView = getLayoutInflater().inflate(R.layout.bubble_view, null);
TextView predict_text = (TextView) bubbleView.findViewById(R.id.predict_text);
predict_text.setText("Hi"); // <--- It don't work :(
default:
break;
}
}
}
[EDIT] []
Add some .XML file
Here is my activity_main.xml
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="com.siddharthks.sampleapp.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Project KHKT"
android:textColor="#AA000000"
android:textSize="21sp" />
<Button
android:id="#+id/start_bubble"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Paste and Predict"
android:textSize="18sp" />
</LinearLayout>
and here is my bubble_view.xml, its just for a
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="16dp"
android:paddingTop="16dp"
android:paddingEnd="16dp"
android:text="Project KHKT"
android:textColor="#AA000000"
android:textSize="21sp" />
<Button
android:id="#+id/predict"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Paste and Predict"
android:textSize="18sp" />
<TextView
android:id="#+id/predict_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="16dp"
android:paddingTop="16dp"
android:paddingEnd="16dp"
android:textColor="#AA000000"
android:textSize="21sp" />
</LinearLayout>
</ScrollView>
Do you have any suggested for me ?
I'm not sure why you inflate the "bubble_view.xml" layout in the activity class. But as your question, there are two main methods to make the button clickable. There is a good explanation in your first comment which is done by Mike M. Once you inflate a layout, it will create a new instance.
Fist answer, Assuming you want everything inside the activity.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button bubble;
private Button predict;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUIViews() // Initialze UI Views
initUIActions() // Initialize Ui Actions
}
private void initUiViews() {
Button bubble = (Button) findViewById(R.id.start_bubble);
Button predict = (Button) bubbleView.findViewById(R.id.predict);
}
private void initUIActions() {
bubble.setOnClickListener(this);// calling onClick() method
predict.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.start_bubble:
startService(new Intent(getApplicationContext(), SimpleService.class));
break;
case R.id.predict:
predict_text.setText("Hi");
break;
default:
break;
}
}
}
and restructure your XML layout as follow. There are few ways to restructure these layouts, I'll write the easiest way, but note that this is not the optimal way.
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="com.siddharthks.sampleapp.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Project KHKT"
android:textColor="#AA000000"
android:textSize="21sp" />
<Button
android:id="#+id/start_bubble"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Paste and Predict"
android:textSize="18sp" />
<!-- include bubble layout file -->
<include layout="#layout/bubble_view.xml" />
</LinearLayout>
Other than the include tag you can add the whole code inside to the Activity layout.
The second answer, Assuming you want activity and Service with a bubble view.
If you are looking for a bubble view, You have to create a Bubble service.
Check this answer: Bubble Example
Official Doc: Android Bubble
Try This it will add Your bubble view in your parent and you can perform any action on that particular Layout from main Layout.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout parent = findViewById(R.id.activity_main); //parent layout.
View childView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.bubble_view,parent,false);
parent.addView(childView);
Button predict = (Button) childView.findViewById(R.id.predict);
TextView predict_text = (TextView) childView.findViewById(R.id.predict_text);
predict.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
predict_text.setText("Hi"); // <--- It don't work :(
}
});
}
}
Add break to the each case statement in the switch.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView predict_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button) findViewById(R.id.start_bubble);
LinearLayout parent = findViewById(R.id.activity_main);
View childView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.bubble_view, parent, false);
parent.addView(childView);
Button predict = (Button) childView.findViewById(R.id.predict);
predict_text = (TextView) childView.findViewById(R.id.predict_text);
predict.setOnClickListener(this);
start.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.predict:
predict_text.setText("Hi");
break;
}
}
}
Im trying to learn how to use android studio, im not unfamiliar with java though.
I tried making a boolean and if it is true, a text changes to "ON", otherwise it will change to "OFF"
My app just crashes when im using USB-Debugging though.
Code:
MainActivity.java
package com.leuchtstein.flashlight;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text = (TextView) findViewById(R.id.textView) ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void triggerlight(View view) {
if (stat == false) {
text.setText("ON");
stat = true;
} else {
text.setText("OFF");
stat = false;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
tools:context="com.leuchtstein.flashlight.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/desc_textview"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Large"
app:layout_constraintHorizontal_bias="0.95"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="triggerlight"
android:text="Turn on/off"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.387" />
Well, thanks in advance.
Don't call
TextView text = (TextView) findViewById(R.id.textView) ;
in initialisation, rather call it in onCreate() method.
This is because Android first initializes the script, and calls onCreate only when setContentView() has been called and it has set up the button, &c. Thus findViewById(int id) can't find anything yet.
Put
text = (TextView) findViewById(R.id.textView);
in onCreate() and put
TextView text;
in initialisation instead.
Try this :
public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView)
}
You haven't provided the logcat or any other any ifo, but one thing I can see here that could go wrong is this :
TextView text = (TextView) findViewById(R.id.textView);
Change your code to look like this :
public class MainActivity extends AppCompatActivity {
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView)
}
So the difference is, you assign a value to your TextView using findViewById, after you have have called setContentView().
All view assignments should be only done after setContentView()is called in activities because that is where you set your root view and when you call findViewById(), the system looks up a view with an id in the root view.
I have some experience with Java, but I am now trying to create an Android app and I do not know how to accept user input. The id of my Edit Text is enterRequestMessage and the name of my XML file is activity_score_entry.xml. Here is the beginning of my Java file.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class ScoreEntry extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score_entry);
}
}
You need to get access to the controls in the xml
public class ScoreEntry extends AppCompatActivity implements View.OnClickListener {
private EditText editText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score_entry);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.button) {
String value = editText.getText().toString();
// use the value here
Log.d(ScoreEntry.class.getCanonicalName(), "The value is: " + value);
}
}
}
And in the xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_score_entry"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
You can adjust the code according to your needs.
I am doing the first experiment with Android and I have the following problem with this simple application.
Basically my application consist into an ImageView showing a background immage, a TextView showing a message and a button.
When the user click this button the text of my TextView have to change and the background immage of my *ImageView also have to change.
So this is my activiy_main.xml file containing the layout of my main activity:
<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:background="#B388FF"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="#+id/android_cookie_image_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scaleType="centerCrop"
android:src="#drawable/before_cookie" />
<TextView
android:id="#+id/status_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="16dp"
android:text="I'm so hungry"
android:textColor="#android:color/white"
android:textSize="34sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="EAT COOKIE"
android:onClick="eatCookie"/>
</LinearLayout>
And this is the code of the previous activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void eatCookie(View v) {
TextView messaggio = (TextView) findViewById(R.id.status_text_view);
messaggio.setText("I'm so full");
ImageView sfondo = (ImageView) findViewById(R.id.android_cookie_image_view);
sfondo.setImageDrawable(Drawable.createFromPath("#drawable/after_cookie"));
}
}
As you can see, when the user click the button it is perform the eatCookie() method that first retrieve the TextView reference and change the text of this TextView. It works fine.
Then it retrieve the reference related to the ImageView and try to change the viewed immage, I have done it by this line:
sfondo.setImageDrawable(Drawable.createFromPath("#drawable/after_cookie"));
In my project I have put the after_cookie.jpg file into the /res/drawable/ folder.
The problem is that it can't work. The default immage of the android_cookie_image_view disappear but is not replaced with the after_cookie.jpg image.
What is wrong? What am I missing? How can I fix this issue?
Try this
sfondo.setImageDrawable(getResources().getDrawable(R.drawable.after_cookie));
Use this instead.
ImageView sfondo = (ImageView) findViewById(R.id.android_cookie_image_view);
sfondo.setImageDrawable(getResources().getDrawable(R.drawable.after_cookie));
And make sure you call that eatCookie function on onCreate.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eatCookie();
}