Am a beginner in android development and am desperately looking for a solution for a challenge i encountered while working on a quiz app.
I have a switch in my SettingsActivity which toggle set a particular text in another activity visible and invisible.
However i have been having problems finding the right logic to reference that text from my SettingsActivity in other to toggle its visibility.
QuizActivity.java
public class QuizActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mExplanationText = (TextView) findViewById(R.id.txtExplanation); //this is the text with which i want the visibility to be controlled from SettingsActivity
}
}
SettingsActivity.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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/explanationText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:fontFamily="cursive"
android:layout_marginBottom="25dp"
android:textColor="#color/settings_text"
android:text="#string/explanation"/>
<Switch
android:id="#+id/explanationSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:checked="true"
android:layout_gravity="center"/>
</LinearLayout>
SettingsActivity.java
private Switch mExplanationSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_settings);
mExplanationSwitch = (Switch) findViewById(R.id.explanationSwitch);
mExplanationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// how do i toggle visibility of mExplanation text in my QuizActivity.java from here?
}
});
}
MainActivity.java
//This is where i start Quiz Activity
private Button startQuiz;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startQuiz = (Button) findViewById(R.id.start);
startQuiz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startQuiz = new Intent(this, QuizActivity.class);
startActivity(beginnerIntent);
});
}
Save Setting in Shared Preferences
mExplanationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences preferences = getSharedPreferences("SETTINGS", MODE_PRIVATE);
Editor editor = preferences.edit();
if(isChecked){
editor.putBoolean("ntoificatoin",isChecked);
}
else
{
editor.putBoolean("ntoificatoin",isChecked);
}
editor.apply();
// how do i toggle visibility of mExplanation text in my QuizActivity.java from here?
}
});
In Your QuizActivity
public class QuizActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mExplanationText = (TextView) findViewById(R.id.txtExplanation); //this is the text with which i want the visibility to be controlled from SettingsActivity
SharedPreferences preferences = getSharedPreferences("SETTINGS", MODE_PRIVATE);
boolean b=preferences.getBoolean("ntoificatoin",false);//it returns stored boolean value else returns false
if(b){
//return true from Settings
//do what you want to
mExplanationText.setText(" "+b);
}
else
{
//return false from Settings
//do what you want to
mExplanationText.setText(" "+b);
}
}
}
if you are looking for how to pass extra info to the QuizActivity here how to use the extra in the intent :
Intent intent = new Intent();
intent.putExtra("stateOfTheSwitch","clicked");
startActivity(intent);
and in the QuizActivity you can retrieve the extra like this :
if(getIntent().getExtras.getString("stateOfTheSwitch").equals("clicked")
//do something
else
//do something else
Related
In my android app I have settings activity, which uses preferences.
There are many preferences such as ListPreference, SwitchPreference, etc., but there aren't one kind of preference that I need.
In this preference I want to:
1. display a title that is constant and will never change (such as other preferences)
2. display text, that will be changed by the app, but NOT by the user.
Most similar preference to this is EditTextPreference, but it's not OK for me, because I don't want user to change displayed text, instead my app will change it. So my preference could be called TextViewPreference.
Good example of what I want is inside the 'Settings' android app, inside the 'device information' category.
Edit:
Code that I would like to use to change summary won't be placed in activity code, and I don't use PreferenceActivity.
In fact, only time when I have to change the summary is when the SettingsActivity is NOT on main thread.
The code below is a complete example of what you are trying to achieve, it shows an example of how to create an info preference that is directly updated based on other preferences (addition of x_pref and y_pref and displaying result in result_pref below) or is updated based on something passed from another activity.
1) DemoActivity----------
public class DemoActivity extends AppCompatActivity{
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_activity);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.demo_preferences, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_settings:
Intent i = new Intent(DemoActivity.this , PrefDemoActivity.class);
i.putExtra("Passed", "Test--##%%&&");
startActivity(i);
break;
default:
throw new RuntimeException("unknown menu selection");
}
return true;
}
}
2) demo_activity.xml----------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Empty"
android:gravity="center"
android:background="#android:color/holo_blue_light"/>
</android.support.constraint.ConstraintLayout>
3) PrefDemoActivity----------
public class PrefDemoActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager mFragmentManager = getFragmentManager();
FragmentTransaction mFragmentTransaction = mFragmentManager
.beginTransaction();
DemoEditPreferences mDemoPrefsFragment = new DemoEditPreferences();
mFragmentTransaction.replace(android.R.id.content, mDemoPrefsFragment);
mFragmentTransaction.commit();
}
}
4) DemEditPreferences----------
public class DemoEditPreferences extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
private SharedPreferences demo_preferences;
private int preferencesToEdit;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
demo_preferences = getActivity().getSharedPreferences("demo_preference",
0);
preferencesToEdit = R.xml.demo_preferences;
String preferenceName = getResources().getString(R.string.pref_sensor_key);
PreferenceManager preferenceManager = getPreferenceManager();
preferenceManager.setSharedPreferencesName(preferenceName);
preferenceManager.setSharedPreferencesMode(0);
getActivity().setTitle("Demo Preferences");
addPreferencesFromResource(preferencesToEdit);
Preference from_another_activity_p = (Preference) findPreference("passed_from_another_activity_key");
if(getActivity().getIntent() != null) {
from_another_activity_p.setSummary(getActivity().getIntent().getStringExtra("Passed"));
}
updateResult();
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
initSummary(getPreferenceScreen().getPreference(i));
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(findPreference(key) != null) {
if(findPreference(key).getKey().equals("x_key")) {
updateResult();
}else if(findPreference(key).getKey().equals("y_key")) {
updateResult();
}
checkPrefValueValidity(findPreference(key));
updatePrefSummary(findPreference(key));
}
}
private void updateResult(){
EditTextPreference x_p = (EditTextPreference) findPreference("x_key");
EditTextPreference y_p = (EditTextPreference) findPreference("y_key");
Preference result_p = (Preference) findPreference("result_key");
result_p.setSummary("( X + Y ) = " + (Float.valueOf(x_p.getText()) + Float.valueOf(y_p.getText())));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCategory = (PreferenceCategory) p;
for (int i = 0; i < pCategory.getPreferenceCount(); i++) {
initSummary(pCategory.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
p.setSummary(editTextPref.getText());
}
}
private void checkPrefValueValidity(Preference p) {
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
if (editTextPref.getText().equals("")) {
// what do you want to do if the value entered is empty
} else {
// maybe only certain values are allowed
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setBackgroundColor(getResources().getColor(android.R.color.white));
return view;
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
5) demo_menu----------
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu_settings"
android:title="Settings"
android:titleCondensed="Settings"
android:orderInCategory="1">
</item>
</menu>
7) demo_preferences----------
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Demo">
<EditTextPreference
android:key="x_key"
android:title="X"
android:defaultValue="0"
android:summary="0"
android:inputType="numberDecimal|numberSigned"
android:selectAllOnFocus="true"
android:singleLine="true">
</EditTextPreference>
<EditTextPreference
android:key="y_key"
android:title="Y"
android:defaultValue="0"
android:summary="0"
android:inputType="numberDecimal|numberSigned"
android:selectAllOnFocus="true"
android:singleLine="true">
</EditTextPreference>
<Preference
android:key="result_key"
android:title="Result"
android:summary="0"> // default summary value if any
</Preference>
<Preference
android:key="passed_from_another_activity_key"
android:title="From another Activity"
android:summary="null"> // default summary value if any
</Preference>
</PreferenceCategory>
</PreferenceScreen>
8) Don't forget to add both activities to the manifest.
What you can do is have an EditTextPreference and disable it. So that the subtitle is displayed but cannot be edited.
findPreference("your-preference-key").setEnabled(false);
I am trying to take the value from my edittextpreference and change the font size of the textviews in my mainActivity layout. Please help me with this guys.I must be doing some silly mistake.Help would be appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(this);
String str=sp.getString("editTextPref","50");
if(sp!=null)
{
Toast.makeText(this,"String value is "+str,Toast.LENGTH_LONG).show();
txt=(TextView) findViewById(R.id.textView);
txt.setTextSize(Float.parseFloat(str));
}
Toast.makeText(this,"String value is :"+str,Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int items=item.getItemId();
switch(items)
{
case R.id.setting:
Toast.makeText(this,"Settings Clicked",Toast.LENGTH_LONG).show();
finish();
Intent i=new Intent(this,Prefs.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
}
Prefs.java
public class Prefs extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
SharedPreferences sp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
// show the current value in the settings screen
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
initSummary(getPreferenceScreen().getPreference(i));
}
}
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
updatePreference(findPreference(key));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory cat = (PreferenceCategory) p;
for (int i = 0; i < cat.getPreferenceCount(); i++) {
initSummary(cat.getPreference(i));
}
} else {
updatePreference(p);
}
}
private void updatePreference(Preference p)
{
if(p instanceof EditTextPreference)
{
EditTextPreference editTextPreference=(EditTextPreference) p;
p.setSummary(editTextPreference.getText());
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
startActivity(new Intent(Prefs.this,MainActivity.class));
Toast.makeText(this,"Pref activity finished",Toast.LENGTH_LONG).show();
}
}
Prefs.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:enabled="false"
android:key="settingCategory"
android:title="Settings"
>
</PreferenceCategory>
<EditTextPreference
android:id="#+id/editTextPref"
android:dialogMessage="I am Dialog Message"
android:dialogTitle="Dialog Title"
android:hint="e.g 25"
android:icon="#mipmap/ic_launcher"
android:key="fontSize"
android:padding="5dp"
android:selectAllOnFocus="true"
android:singleLine="true"
android:summary="Changes Font Size of Overall App"
android:title="Change Font Size" />
</PreferenceScreen>
You should be reading value for key fontSize not the name of id field of EditTextPreference. Change your code in your MainActivity like this:
SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(this);
String str=sp.getString("fontSize","50");
Is there anyway of showing only my webview once loading has complete? at the moment i have a little webview Fragment on my homescreen but it takes a while to load.I want to show only once loading completes because at the moment its a white screen until loading completes.This does not look the greatest. I tried to add a progress bar but for some reason that does not work in my fragment either.
Ive tried to add the code posted as an answer but it makes no difference. i think its because it a fragment that im having the issues as the progress par works in my main activity webviews.
public class WebViewFragment extends Fragment {
WebView wv;
private String NEWS = "mywebsite goes here";
#Override
public void onSaveInstanceState(Bundle outState) {
wv.saveState(outState);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(getContext(), "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(getContext(), "portrait", Toast.LENGTH_SHORT).show();
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ProgressBar Pbar;
View view = inflater.inflate(R.layout.webviewfrag, null, false);
if (savedInstanceState == null) {
((WebView )view.findViewById(R.id.NewsFeedWbview)).restoreState(savedInstanceState);
wv = (WebView) view.findViewById(R.id.NewsFeedWbview);
wv.setScrollbarFadingEnabled(false);
Pbar = (ProgressBar) view.findViewById(R.id.pBwvf);
final TextView tv = (TextView) view.findViewById(R.id.tV69);
wv.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100 && Pbar.getVisibility() == ProgressBar.GONE) {
Pbar.setVisibility(ProgressBar.VISIBLE);
tv.setVisibility(View.VISIBLE);
}
Pbar.setProgress(progress);
if (progress == 100) {
Pbar.setVisibility(ProgressBar.GONE);
tv.setVisibility(View.GONE);
}
}
});
wv.getSettings().setJavaScriptEnabled(true);
wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
if (Build.VERSION.SDK_INT >= 19) {
// chromium, enable hardware acceleration
wv.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
// older android version, disable hardware acceleration
wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
wv.canGoBackOrForward(5);
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setUseWideViewPort(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.setPadding(0, 0, 0, 0);
wv.loadUrl(NEWS);
}
return view;
}
}
Here my code:
Activity:
public class WebViewActivity extends Activity {
private WebView webView;
private EditText urlEditText;
private ProgressBar progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
urlEditText = (EditText) findViewById(R.id.urlField);
webView = (WebView) findViewById(R.id.webView);
webView.setWebChromeClient(new MyWebViewClient());
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
Button openUrl = (Button) findViewById(R.id.goButton);
openUrl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String url = urlEditText.getText().toString();
if (validateUrl(url)) {
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
WebViewActivity.this.progress.setProgress(0);
}
}
private boolean validateUrl(String url) {
return true;
}
});
}
private class MyWebViewClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
WebViewActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.web_view, menu);
return true;
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
}
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"
tools:context=".WebViewActivity" >
<LinearLayout
android:id="#+id/urlContainer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/urlField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="3"
android:hint="Enter URL to open" />
<Button
android:id="#+id/goButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Open" />
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/urlContainer" />
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/progressBar" />
</RelativeLayout>
Use below code
wv.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
}
});
This is the code:
public class MainActivity extends Activity
{
private TextView textView2;
private Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView2=(TextView)findViewById(R.id.textView1);
button2=(Button)findViewById(R.id.button1);
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url="http://stackoverflow.com/";
try{
Document doc=Jsoup.connect(url).get();
Elements elem=doc.select("meta[name=twitter:domain]");
String title1=elem.attr("content");
textView2.setText(title1);
}
catch(Exception e){
}
}
});
}}
This is the xml code:
<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: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="com.example.jsouptest.MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="111dp"
android:text="TextView"
android:textSize="100dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentTop="true"
android:layout_marginLeft="22dp"
android:layout_marginTop="34dp"
android:text="Display" />
It isn't displaying the content in the textview on clicking the
button.
I have added permission for internet in the manifest file.
You can not call Network on main thread. You must call async task to make network calls. When you click on button execute a async task and then do your stuff there.
Below Code will Help:
public class MainActivity extends Activity {
TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new GetStringTask().execute();
}
});
}
private class GetStringTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String url = "http://stackoverflow.com/";
Document doc = null;
try {
doc = Jsoup.connect(url).get();
Elements elem = doc.getElementsByTag("title");
String title1 = elem.html();
return title1;
} catch (IOException e) {
e.printStackTrace();
return "Exception";
}
}
#Override
protected void onPostExecute(String title) {
textView1.setText(title);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
the code above sets the TextView label to "Stack Overflow".
I want the button to show some texts when it is clicked. When we click the 'formula' button, a new blank page should open up in the phone showing the layout of the activity.. Here are my codes
MainActivity.java
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "";
// ....
public void sendMessage(View view) {
Intent intent = new Intent(MainActivity.this, FormulaActivity.class);
EditText editText = (EditText) findViewById(R.id.edit);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
// Do something in response to button
startActivity(intent);
FormulaActivity.java
public class FormulaActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
MainActivity.xml (button coding)
<Button
android:id="#+id/formula"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendMessage"
android:text="Formula" />
You just need to intialize the Button and EditText inside your MainActivity.java
XML Layout File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
/>
<Button
android:id="#+id/formula"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Formula"
android:gravity="bottom"
/>
public class MainActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Button F=(Button)findViewById(R.id.formula);
EditText editText = (EditText) findViewById(R.id.edit);
F.setOnClickListener(new View.onClickListener()
{
public void onClick()
{
sendMessage();
}
}
}
public void sendMessage()
{
String message = editText.getText().toString();
Intent intent = new Intent(MainActivity.this, FormulaActivity.class);
intent.putExtra("EXTRA_MESSAGE", message);
startActivity(intent);
}
}
public class FormulaActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra("EXTRA_MESSAGE");
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
Your public final static String EXTRA_MESSAGE = ""; is empty string. Try changing it to any valued string.
Hope this will help you.