How to integrate radiobuttons in Tabhost? - android

I've made a full working three TAB-GUI in Android SDK (2.3.3) but I want to integrate several radiobuttons and one radiogroup into a TAB. I'm a android-newbe so I hope somebody can help me?
Hereby the main-code and the according Class-code:
MAIN
package com.example.androidtablayout;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class AndroidTabLayoutActivity extends TabActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHost tabHost = getTabHost();
// Tab for Dag
TabSpec dagspec = tabHost.newTabSpec("Dag");
dagspec.setIndicator("DagRooster", getResources().getDrawable(R.drawable.icon_dag_tab));
Intent dagIntent = new Intent(this, DagActivity.class);
dagspec.setContent(dagIntent);
// Tab for Norm
TabSpec normspec = tabHost.newTabSpec("Norm");
// setting Title and Icon for the Tab
normspec.setIndicator("Normaal", getResources().getDrawable(R.drawable.icon_norm_tab));
Intent normIntent = new Intent(this, NormActivity.class);
normspec.setContent(normIntent);
// Tab for Instel
TabSpec instelspec = tabHost.newTabSpec("Instel");
instelspec.setIndicator("Info", getResources().getDrawable(R.drawable.icon_setting_tab));
Intent instelIntent = new Intent(this, InstelActivity.class);
instelspec.setContent(instelIntent);
// Adding all TabSpec to TabHost
tabHost.addTab(dagspec); // Adding photos tab
tabHost.addTab(normspec); // Adding songs tab
tabHost.addTab(instelspec); // Adding videos tab
}
}
NORM-CLASS code
package com.example.androidtablayout;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class NormActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.instel_layout);
}
}

In the activity you want the radioButtons, .. Not TabActivty.. try something like this below. NB: pay atention to the radiobutton stuff.. I ripped some code for location management out before posting. But the radioButton logic will get you what you want.
public class Distribute extends Activity implements OnClickListener {
#SuppressWarnings("unused")
private static final String DEBUG_FLAG = "DEBUG_FLAG";
private static final String SAVE_PREFS = "save_prefs";
private static RadioButton mUserTypeRadioButton1;
private static RadioButton mUserTypeRadioButton2;
private static RadioButton mUserTypeRadioButton3;
private static RadioButton mUserTypeRadioButton4;
private static CheckBox mSavePrefs;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textview = new TextView(this);
textview.setText("Distribution");
setContentView(R.drawable.configup);
Button button = (Button)findViewById(R.id.btn_configup1);
mUserTypeRadioButton1 = (RadioButton) findViewById(R.id.rb_configup1);
mUserTypeRadioButton2 = (RadioButton) findViewById(R.id.rb_configup2);
mUserTypeRadioButton3 = (RadioButton) findViewById(R.id.rb_configup3);
mUserTypeRadioButton4 = (RadioButton) findViewById(R.id.rb_configup4);
mSavePrefs = (CheckBox) findViewById(R.id.cb_config1);
button.setOnClickListener(this);
}
public void onClick(View v) {
Intent i = new Intent();
Bundle extras = new Bundle();
int userType = 0;
int savePrefs = 0;
//i.putExtra("passLoc", currLoc);
i.setClass(getApplicationContext(), Clevel.class);
i.putExtras(extras);
if (mUserTypeRadioButton1.isChecked()) {
userType = 1;
}
else if (mUserTypeRadioButton2.isChecked()) {
userType = 2;
}
else if (mUserTypeRadioButton3.isChecked()) {
userType = 3;
}
else if (mUserTypeRadioButton4.isChecked()) {
userType = 4;
}
if (mSavePrefs.isChecked()) {
savePrefs = 1;
}
else {
savePrefs = 0;
}
if (userType == 4){
Toast.makeText(this, "Ad-Hoc Reporting is not Yet Implemented", 5).show();
i.putExtra("SetTab", 1);
}
else if (userType == 0){
Toast.makeText(this, "Please Select a Report Group", 5).show();
i.putExtra("SetTab", 1);
}
else {
i.putExtra("ds", userType);
i.putExtra("prefs", savePrefs);
i.putExtra("SetTab", 2);
}
startActivity(i);
}
}
In your TabHost you will need something like this to manage the Intent/Bundle
/**
* Distribute TabHost--------------------------------
*/
intent = new Intent().setClass(this, Distribute.class);
if(mTab == 1){
mPos = extras.getInt("lvPos");
mPrefs = extras.getInt("prefs");
intent.putExtra("lvPos", mPos);
intent.putExtra("prefs", mPrefs);
}
spec = tabHost.newTabSpec("Config").setIndicator("Distribute-It!",
res.getDrawable(R.drawable.gixconfig))
.setContent(intent);
tabHost.addTab(spec);
And the needed XML.. Just a start, you'll need to wrap this inside your XML for the screen you want radioButtons to show up
<RadioGroup
android:id="#+id/rg_configup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
<RadioButton
android:id="#+id/rb_configup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sales"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</RadioButton>
<RadioButton
android:id="#+id/rb_configup2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Regional"
android:layout_above="#+id/rb_configup1"
android:layout_alignLeft="#+id/rb_configup1"
>
</RadioButton>
<RadioButton
android:id="#+id/rb_configup3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Global"
android:layout_above="#+id/rb_configup2"
android:layout_alignLeft="#+id/rb_configup1"
>
</RadioButton>
<RadioButton
android:id="#+id/rb_configup4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ad-hoc"
android:layout_above="#+id/rb_configup3"
android:layout_alignLeft="#+id/rb_configup1"
>
</RadioButton>
</RadioGroup>

Related

How do I get each textview resource amount and add them all together into a single variable to be converted into a two sliced pie chart?

This is the code I have been working on for a while. The only issue is I cannot seem to be able to get the sum of values input into the editText fields that are dynamically added into the program and then place them into a pie chart. The data is to be transferred from the second activity to the third where the third activity will add up all resource amounts and display them into a pie chart.
SecondActivity.class
package com.example.a4mob;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.drawerlayout.widget.DrawerLayout;
import java.util.ArrayList;
import java.util.List;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
private LinearLayout linearLayout;
private Button add;
//for button add resource
List<String> ColourList = new ArrayList<>();
ArrayList<Results> resultList = new ArrayList<>();
private Button submit;
private Number uinput;
#Override
protected void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.secondactivity);
// drawer layout instance to toggle the menu icon to open
// drawer and back button to close drawer
drawerLayout = findViewById(R.id.my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close);
// pass the Open and Close toggle for the drawer layout listener
// to toggle the button
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
// to make the Navigation drawer icon always appear on the action bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar;
actionBar = getSupportActionBar();
// Define ColorDrawable object and parse color
// using parseColor method
// with color hash code as its parameter
ColorDrawable colorDrawable
= new ColorDrawable(Color.parseColor("grey"));
// Set BackgroundDrawable
actionBar.setBackgroundDrawable(colorDrawable);
//Adds more objects
linearLayout = findViewById(R.id.layout_list);
add = findViewById(R.id.CreateNew);
add.setOnClickListener(this);
ColourList.add("grey");
ColourList.add("green");
ColourList.add("blue");
ColourList.add("yellow");
// Creating submit button click listener
submit = findViewById(R.id.Submit);
submit.setOnClickListener(this);
}
public void onClick(View view){
switch (view.getId()){
case R.id.CreateNew:
addView();
break;
case R.id.Submit:
if(isValid()){
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("list", resultList);
intent.putExtras(bundle);
startActivity(intent);
}
break;
}
}
private boolean isValid() {
resultList.clear();
boolean valid = true;
for(int i = 0; i < linearLayout.getChildCount(); i++){
View resultView = linearLayout.getChildAt(i);
EditText resultName = (EditText) resultView.findViewById(R.id.RName);
EditText resultNumber = (EditText) resultView.findViewById(R.id.RAmount);
AppCompatSpinner COP = (AppCompatSpinner) resultView.findViewById(R.id.ColourOP);
Results results = new Results();
if(!resultName.getText().toString().equals("")){
results.setResName(resultName.getText().toString());
}else{
valid = false;
break;
}
if(!resultNumber.getText().toString().equals("")){
results.setResAmount(Integer.parseInt(resultNumber.getText().toString()));
}else{
valid = false;
break;
}
if(COP.getSelectedItemPosition()!=0){
}else{
valid = false;
break;
}
resultList.add(results);
}
if(resultList.size() == 0){
valid = false;
Toast.makeText(this, "Complete all fields first", Toast.LENGTH_SHORT).show();
} else if(!valid){
Toast.makeText(this, "Enter details correctly", Toast.LENGTH_SHORT).show();
}
return valid;
}
public void addAmount(){
for(int i = 0; i < linearLayout.getChildCount(); i++) {
View resultView = linearLayout.getChildAt(i);
EditText resultNumber = (EditText) resultView.findViewById(R.id.RAmount);
Results results = new Results();
}
}
private void sub(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please input inventory space:");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
uinput = input.getInputType();
changeAct();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private void changeAct(){
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
private void addView(){
View newResource = getLayoutInflater().inflate(R.layout.row_add_data, null, false);
ImageView imageClose = (ImageView)newResource.findViewById(R.id.Remove);
TextView RN = (TextView) newResource.findViewById(R.id.RName);
TextView RA = (TextView) newResource.findViewById(R.id.RAmount);
AppCompatSpinner COP = (AppCompatSpinner) newResource.findViewById(R.id.ColourOP);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, ColourList);
COP.setAdapter(arrayAdapter);
imageClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeView(newResource);
}
});
linearLayout.addView(newResource);
}
private void removeView(View view){
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
super.onPointerCaptureChanged(hasCapture);
}
}
ThirdActivity.class
package com.example.a4mob;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class ThirdActivity extends AppCompatActivity {
RecyclerView recycle_results;
ArrayList<Results> resultList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdactivity);
recycle_results = findViewById(R.id.res_results);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
recycle_results.setLayoutManager(linearLayoutManager);
resultList = (ArrayList<Results>) getIntent().getExtras().getSerializable("list");
recycle_results.setAdapter(new ResultsAdapter(resultList));
}
}
Results.class
package com.example.a4mob;
import java.io.Serializable;
public class Results implements Serializable {
public String resourceName;
public int resourceAmount;
public int totalAmount;
public Results(){
}
public int getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(int totalAmount) {
this.totalAmount = totalAmount;
}
public int getResAmount() {
return resourceAmount;
}
public void setResAmount(int resourceAmount) {
this.resourceAmount = resourceAmount;
}
public Results(String resourceName, int resourceAmount){
this.resourceName = resourceName;
this.resourceAmount = resourceAmount;
}
public String getResName() {
return resourceName;
}
public void setResName(String resourceName) {
this.resourceName = resourceName;
}
}
ResultsAdapter.class
package com.example.a4mob;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ResultsAdapter extends RecyclerView.Adapter<ResultsAdapter.ResultsView> {
ArrayList<Results> resultList = new ArrayList<>();
int total;
public ResultsAdapter(ArrayList<Results> resultList) {
this.resultList = resultList;
}
#NonNull
#Override
public ResultsView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_results,parent,false);
return new ResultsView(view);
}
#Override
public void onBindViewHolder(#NonNull ResultsView holder, int position) {
Results results = resultList.get(position);
holder.resourceName.setText(results.getResName());
holder.resourceAmount.setText(String.valueOf(results.getResAmount()));
}
#Override
public int getItemCount() {
return resultList.size();
}
public class ResultsView extends RecyclerView.ViewHolder{
TextView resourceName, resourceAmount, resourceTotal;
public ResultsView(#NonNull View itemView) {
super(itemView);
resourceName = (TextView) itemView.findViewById(R.id.resNa);
resourceAmount = (TextView) itemView.findViewById(R.id.resAm);
resourceTotal = (TextView) itemView.findViewById(R.id.resTot);
}
}
}
thirdactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".ThirdActivity">
<LinearLayout
android:id="#+id/layoutThird"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/res_results"
android:layout_width="match_parent"
android:layout_height="match_parent"></androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
row_results.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardBackgroundColor="#color/white"
android:layout_margin="5dp"
android:layout_marginBottom="20dp"
app:cardCornerRadius="10dp"
app:cardElevation="10dp">
<LinearLayout
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1"
android:layout_marginBottom="0dp">
<TextView
android:id="#+id/resNa"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Name"
android:textSize="18sp"
android:textColor="#color/black"></TextView>
<TextView
android:id="#+id/resAm"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Amount"
android:textSize="14sp"
android:textColor="#color/black"></TextView>
<TextView
android:id="#+id/resTot"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Amount"
android:textSize="14sp"
android:textColor="#color/black"></TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>

change the text in another activity

I have a button in Activity A, which changes the text in it when clicked. There is an Activity B in which I need the TextView to become visible and its text to be the same as the text in the button on the Activity A. Please help.
Activity A
package com.example.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.annotation.Nullable;
public class SmActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sm);
Button btn_apple = (Button) findViewById(R.id.button_apple);
Button btn_cherry = (Button) findViewById(R.id.button_cherry);
Button btn_orange = (Button) findViewById(R.id.button_orange);
Button btn_waterLemon = (Button) findViewById(R.id.button_waterlemon);
View.OnClickListener appleListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_apple.setText("1");
}
else {
int i = Integer.parseInt(btn_apple.getText().toString());
btn_apple.setText(String.valueOf(i + 1));
i = i;
}
}
};
View.OnClickListener cherryListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_cherry.setText("1");
}
else {
int j = Integer.parseInt(btn_cherry.getText().toString());
btn_cherry.setText(String.valueOf(j + 1));
j = j;
}
}
};
View.OnClickListener orangeListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_orange.setText("1");
}
else {
int k = Integer.parseInt(btn_orange.getText().toString());
btn_orange.setText(String.valueOf(k + 1));
k = k;
}
}
};
View.OnClickListener waterListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_waterLemon.setText("1");
} else {
int q = Integer.parseInt(btn_waterLemon.getText().toString());
btn_waterLemon.setText(String.valueOf(q + 1));
q = q;
}
}
};
btn_apple.setOnClickListener(appleListener);
btn_cherry.setOnClickListener(cherryListener);
btn_orange.setOnClickListener(orangeListener);
btn_waterLemon.setOnClickListener(waterListener);
}
public void OnClickBsk(View view){
Intent intent = new Intent(SmActivity.this, BasketActivity.class);
startActivity(intent);
}
public void OnClickProfile(View view){
Intent intent = new Intent(SmActivity.this, ProfileActivity.class);
startActivity(intent);
}
}
Do this In Activity A when you click button to go to next Activity B
btn.setOnClickListener(v -> {
Intent i = new Intent(AActivity.this,BActivity.class);
// This below line sends Key- btnText and Value- Apple
i.putExtra("btnText","Apple");
startActivity(i);
});
In BActivity do this to button
// Here you receives data from activity a with the help of Key- btnText
btn.setText(getIntent().getStringExtra("btnText"));
This is a simple way to do this.
I Have Solved the answer for you,
Minor Explanations is in the comments in code.
Use this code as a concept and apply changes to yours based on your requirement.
XML of Activity A:
<?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"
tools:context=".ActivityA">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text Before Button Click"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="#+id/text_to_change"
android:textSize="20sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_to_change"
android:id="#+id/change_text_btn"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:text="Change Text and Start Activity B"
/>
</RelativeLayout>
Java of Activity A
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity);
TextView textView;
Button button;
textView=findViewById(R.id.text_to_change);
button=findViewById(R.id.change_text_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newtext="New Text From Activity A";
textView.setText(newtext);
Intent intent=new Intent(ActivityA.this,ActivityB.class);
intent.putExtra("Change", newtext);//this string will be
//accessed by activityB
startActivity(intent);
}
});
}
}
XML of Activity B:
<?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"
tools:context=".ActivityB">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Waiting for New Text"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="#+id/new_textview"
android:textSize="20sp"
android:visibility="gone"
/>
</RelativeLayout>
Java of Activity B:
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
TextView textView;
textView=findViewById(R.id.new_textview);
// Below if block is looking for an intent, if it gets it and
// there is content in the extras with key "Change",
// it will make the textview in xml visible and update its string
// based on value set by Activity A
if(savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
Toast.makeText(ActivityB.this, "Can't Get the Intent", Toast.LENGTH_LONG).show();
} else {
String get_String = extras.getString("Change");
textView.setVisibility(View.VISIBLE);// be default i have set the visibility to gone in xml
//here it will get visible and then filled with the string sent by the intent in activity A
textView.setText(get_String);
}
}
}
}

Button Display Android Eclipse

I have added a toggleButton, but it is not showing up and I cannot figure out why. I have completed the Android tutorial, and have looked back at the code, as well as many other sources. The objective is to have the program pause when the button is ON. At the moment, the button will not even show up on the user interface. Any suggestions?
<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=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:onClick="pauseCounter" />
</RelativeLayout>
package com.evorlor.counter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent counter = new Intent(MainActivity.this, Counter.class);
startActivity(counter);
}
public void pauseCounter(View view) {
Intent pause = new Intent(this, Pause.class);
startActivity(pause);
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_main, menu);
// return true;
// }
}
package com.evorlor.counter;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Pause extends Activity{
public void onCreate(Bundle instPause) {
super.onCreate(instPause);
TextView tv = new TextView(this);
tv.setTextSize(250);
tv.setText("PAUSE");
setContentView(tv);
}
}
Here is my Counter class. It is messy. Sorry. This is as close as I have come so far. Help would be very appreciated! I have spent a lot of time on this measly button! Thanks!
package com.evorlor.counter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.widget.TextView;
import android.widget.ToggleButton;
public class Counter extends Activity {
private int count = 0;
private int hiCount = 0;
private boolean capCount = false;
public void onCreate(Bundle instCounter) {
super.onCreate(instCounter);
TextView tv = new TextView(this);
tv.setTextSize(250);
if (count < 10000 && capCount == false) {
tv.setText(Integer.toString(count));
} else {
capCount = true;
if (count >= 10000) {
hiCount += 10;
count -= 10000;
}
if (hiCount < 100) {
tv.setText(hiCount + "k+" + count);
} else {
tv.setText("Over\n100k");
}
}
tv.setGravity(Gravity.CENTER);
setContentView(tv);
ToggleButton butPause = new ToggleButton(this);
if (butPause == null) {
Intent pause = new Intent(this, Pause.class);
startActivity(pause);
}
}
// public void pauseCounter(View view) {
// Intent pause = new Intent(this, Pause.class);
// startActivity(pause);
// }
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent counter = new Intent(MainActivity.this, Counter.class);
startActivity(counter);
}
You are starting a new activity right away. thats not a good idea.
You are going to see what is in your Counter activity, not what is in your main activity, reason you don't see your toggle button. Comment out startActivity() just to check.

Android change tab without losing data

I'm working with tabs in android, according to my requirement I need to open a popup containing 5 tabs. That is, I have a Fragment where I have to open a DialogFragment and this DialogFragment need to show my 5 tabs. So far so quiet! Could enter each content on their respective tabs.
But the problem is that when I change the tab, the values ​​that were entered in another tab are clean. example:
I go into tab1 fills any value in a text field and then when I switch to tab2 tab1 back to the value it had before entered is lost.
Given this scenario, how do I retain the values ​​that were filled to the brim change? Follow the code below to explain further.
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import br.com.company.R;
import br.com.company.beans.Ordem;
import br.com.company.dispatcher.IDispacher;
import br.com.company.fragment.helper.IFragmentCo;
import br.com.company.bo.IClasseBO;
public class TabsFragment extends DialogFragment implements OnTabChangeListener {
private static final String TAG = "FragmentTabs";
public static final String TAB_DADOS_CLIENTE = "dadosCliente";
public static final String TAB_DEFEITO_FALHA = "defeitoFalha";
public static final String TAB_SERVICOS = "servico";
public static final String TAB_MATERIAIS = "material";
public static final String TAB_OBSERVACAO = "observacao";
private View mRoot;
private Button enviar;
private Button cancelar;
private Spinner classe;
private TabHost mTabHost;
private Ordem ordem;
private IClasseBO classeBO;
private IDispacher dispatch;
private IFragmentCo ifrag;
private int mCurrentTab;
public TabsFragment(IFragmentCo ifrag, Ordem ordem) {
this.ordem = ordem;
this.ifrag = ifrag;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.ordem_encerramento, null);
enviar = (Button) mRoot.findViewById(R.ordem_encerramento.enviar);
cancelar = (Button) mRoot.findViewById(R.ordem_encerramento.cancelar);
cancelar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TabsFragment.this.dismiss();
}
});
mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
setupTabs();
return mRoot;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(mCurrentTab);
mTabHost.getTabContentView().addView(addView(R.layout.dados_cliente));
}
private void setupTabs() {
mTabHost.setup(); // importante!
mTabHost.addTab(newTab(TAB_DADOS_CLIENTE, R.string.tab_dados_cliente, R.ordem_encerramento.dados_cliente));
mTabHost.addTab(newTab(TAB_DEFEITO_FALHA, R.string.tab_defeito_falha, R.ordem_encerramento.defeito_falha));
mTabHost.addTab(newTab(TAB_SERVICOS, R.string.tab_servico, R.ordem_encerramento.servico));
mTabHost.addTab(newTab(TAB_MATERIAIS, R.string.tab_material, R.ordem_encerramento.material));
mTabHost.addTab(newTab(TAB_OBSERVACAO, R.string.tab_observacao, R.ordem_encerramento.observacao));
}
private View addView(int resource) {
LayoutInflater layoutInflater = (LayoutInflater)getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(resource, null);
return view;
}
private TabSpec newTab(String tag, int labelId, int tabContentId) {
Log.d(TAG, "buildTab(): tag=" + tag);
View view = LayoutInflater.from(mTabHost.getContext()).inflate(R.layout.tabs_bg_view, null);
TextView tv = (TextView) view.findViewById(R.id.tabsText);
tv.setText(labelId);
TabSpec tabSpec = mTabHost.newTabSpec(tag);
tabSpec.setIndicator(view);
tabSpec.setContent(tabContentId);
return tabSpec;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onTabChanged(String tabId) {
Log.d(TAG, "onTabChanged(): tabId=" + tabId);
View view = null;
if (TAB_DADOS_CLIENTE.equals(tabId)) {
mTabHost.getTabContentView().removeAllViews();
mTabHost.getTabContentView().addView(addView(R.layout.dados_cliente));
mTabHost.setCurrentTab(0);
} else if (TAB_DEFEITO_FALHA.equals(tabId)) {
view = new DefeitoFalhaView().createView(getActivity());
mTabHost.getTabContentView().addView(view);
mTabHost.setCurrentTab(1);
} else if (TAB_SERVICOS.equals(tabId)) {
mTabHost.getTabContentView().removeAllViews();
mTabHost.getTabContentView().addView(addView(R.layout.servico));
mCurrentTab = 2;
} else if (TAB_MATERIAIS.equals(tabId)) {
mTabHost.getTabContentView().removeAllViews();
mTabHost.getTabContentView().addView(addView(R.layout.materiais));
mCurrentTab = 3;
} else if (TAB_OBSERVACAO.equals(tabId)) {
mTabHost.getTabContentView().removeAllViews();
mTabHost.getTabContentView().addView(addView(R.layout.observacao));
mCurrentTab = 4;
}
}
public View getmRoot() {
return mRoot;
}
}
File xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/White"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="30dip"
android:layout_gravity="center_vertical"
android:orientation="horizontal"
android:paddingRight="10dip" >
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:paddingLeft="10dip"
android:text="Devolver OS"
android:textColor="#color/Black" />
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="#+ordem_encerramento/cancelar"
style="#style/ButtonNovo"
android:layout_marginLeft="10dip"
android:text="Cancelar" />
<Button
android:id="#+ordem_encerramento/enviar"
style="#style/ButtonNovo"
android:layout_marginLeft="10dip"
android:text="Enviar" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#xml/menu_bg" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="40dip" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dip" >
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#EFEFEF" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<FrameLayout
android:id="#+ordem_encerramento/dados_cliente"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+ordem_encerramento/defeito_falha"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+ordem_encerramento/servico"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+ordem_encerramento/material"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+ordem_encerramento/observacao"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
</ScrollView>
</LinearLayout>
Try storing those values somewhere e.g.SharedPreferences or static variable and setting them back in onTabChanged().
TabGroupActivity.java
import java.util.ArrayList;
import com.data.DataClass;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
/**
* The purpose of this Activity is to manage the activities in a tab. Note:
* Child Activities can handle Key Presses before they are seen here.
*
* #author Eric Harlow
*/
public class TabGroupActivity extends ActivityGroup {
private ArrayList<String> mIdList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mIdList == null)
mIdList = new ArrayList<String>();
}
/**
* This is called when a child activity of this one calls its finish method.
* This implementation calls {#link LocalActivityManager#destroyActivity} on
* the child activity and starts the previous activity. If the last child
* activity just called finish(),this activity (the parent), calls finish to
* finish the entire group.
*/
#Override
public void finishFromChild(Activity child) {
LocalActivityManager manager = getLocalActivityManager();
int index = mIdList.size() - 1;
if (index < 1) {
finish();
return;
}
manager.destroyActivity(mIdList.get(index), true);
mIdList.remove(index);
index--;
String lastId = mIdList.get(index);
Intent lastIntent = manager.getActivity(lastId).getIntent();
Window newWindow = manager.startActivity(lastId, lastIntent);
setContentView(newWindow.getDecorView());
}
/**
* Starts an Activity as a child Activity to this.
*
* #param Id
* Unique identifier of the activity to be started.
* #param intent
* The Intent describing the activity to be started.
* #throws android.content.ActivityNotFoundException.
*/
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id,
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
mIdList.add(Id);
setContentView(window.getDecorView());
}
}
/**
* The primary purpose is to prevent systems before
* android.os.Build.VERSION_CODES.ECLAIR from calling their default
* KeyEvent.KEYCODE_BACK during onKeyDown.
*/
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// preventing default implementation previous to
// android.os.Build.VERSION_CODES.ECLAIR
// onBackPressed();//Added after
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Overrides the default implementation for KeyEvent.KEYCODE_BACK so that
* all systems call onBackPressed().
*/
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyUp(keyCode, event);
}
/**
* If a Child Activity handles KeyEvent.KEYCODE_BACK. Simply override and
* add this method.
*/
public void onBackPressed() {
int length = mIdList.size();
if (length > 1) {
Activity current = getLocalActivityManager().getActivity(
mIdList.get(length - 1));
if (DataClass.isTemp()) {
overridePendingTransition(R.anim.slide_in_up,
R.anim.slide_in_up);
}
current.finish();
}
}
}
MainTab.java
import com.data.DataClass;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.LinearLayout.LayoutParams;
public class MainTabInfoMe extends TabActivity {
public final static int HOME = 1;
public final static int DIARY = 2;
public final static int PROGRESS = 3;
long transactionID = -1;
public static TabHost tabHost;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mytabs);
MyView view = null;
tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
intent = new Intent().setClass(this, TabGroup1Activity.class);
view = new MyView(this, R.drawable.home_select, R.drawable.home, "");
view.setFocusable(true);
spec = tabHost.newTabSpec("Home").setIndicator(view).setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, TabGroup2Activity.class);
view = new MyView(this, R.drawable.prof_select, R.drawable.prof, "");
view.setFocusable(true);
spec = tabHost.newTabSpec("Diary").setIndicator(view)
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, TabGroup3Activity.class);
view = new MyView(this, R.drawable.bus_select, R.drawable.bus, "");
view.setFocusable(true);
spec = tabHost.newTabSpec("progress").setIndicator(view)
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).getLayoutParams().height =
LayoutParams.WRAP_CONTENT;
tabHost.getTabWidget().getChildAt(1).getLayoutParams().height =
LayoutParams.WRAP_CONTENT;
tabHost.getTabWidget().getChildAt(2).getLayoutParams().height =
LayoutParams.WRAP_CONTENT;
if (MyApplication.getFrom().equals("Home")) {
tabHost.setCurrentTab(0);
} else if (MyApplication.getFrom().equals("Diary")) {
tabHost.setCurrentTab(1);
} else if (MyApplication.getFrom().equals("progress")) {
tabHost.setCurrentTab(2);
}
int type = 0;
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey("from")) {
type = getIntent().getExtras().getInt("from");
switch (type) {
case HOME:
tabHost.setCurrentTab(0);
case DIARY:
tabHost.setCurrentTab(1);
case PROGRESS:
tabHost.setCurrentTab(2);
default:
tabHost.setCurrentTab(0);
}
}
}
}
public long getTransactionID() {
return transactionID;
}
public void setTransactionID(long l) {
transactionID = l;
}
public void switchTabSpecial(int tab) {
tabHost.setCurrentTab(tab);
}
class ChangeTabReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
tabHost = getTabHost();
tabHost.setCurrentTab(1);
}
}
private class MyView extends LinearLayout {
ImageView iv;
public MyView(Context c, int drawable, int drawableselec, String label) {
super(c);
iv = new ImageView(c);
StateListDrawable listDrawable = new StateListDrawable();
listDrawable.addState(SELECTED_STATE_SET, this.getResources()
.getDrawable(drawable));
listDrawable.addState(ENABLED_STATE_SET, this.getResources()
.getDrawable(drawableselec));
iv.setImageDrawable(listDrawable);
iv.setBackgroundColor(Color.TRANSPARENT);
iv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, (float) 0.0));
iv.setPadding(0, 0, 0, 5);
setGravity(Gravity.CENTER);
addView(iv);
}
}
#Override
protected void onPause() {
super.onPause();
if( DataClass.isTemp()){
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_in_up);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
finish();
}
}
FirstTab of class
public class TabGroup1Activity extends TabGroupActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("OptionsActivity", new Intent(this,
MainActivity.class));
}
#Override
public void onBackPressed() {
super.onBackPressed();
DataClass.setTemp(false);
finish();
}
}
SecondTab of class
public class TabGroup2Activity extends TabGroupActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("OptionsActivity", new Intent(this,
MainActivity.class));
}
#Override
public void onBackPressed() {
super.onBackPressed();
DataClass.setTemp(false);
finish();
}
}
thirdTab of class
public class TabGroup1Activity extends TabGroupActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("OptionsActivity", new Intent(this,
MainActivity.class));
}
#Override
public void onBackPressed() {
super.onBackPressed();
DataClass.setTemp(false);
finish();
}
}
static variable class
import android.app.Application;
public class MyApplication extends Application {
private static String from = "Home";
public static String getFrom() {
return from;
}
public static void setFrom(String fromPage) {
from = fromPage;
}
}
xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TabHost android:id="#android:id/tabhost" android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TabWidget android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#drawable/topbarbck"/>
</RelativeLayout>
</TabHost>
</LinearLayout>
put all file and check it
Thanks to all who tried to help me!
I do not have much experience with android but from what I saw, the classes must be executed according to the hierarchy proposed by android. That is, in my case I have a main activity which calls the mine fragments and through one of the fragments I had to call a DialogFragment and this would inflate DialogFragment several Views (my tabs), so I have the following structure:
Activity > Fragment > DialogFragment > Views
Based on this solution for my case was thus:
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
public class OrdemEncerramentoFragment extends DialogFragment implements OnTabChangeListener {
private static final String TAG = "FragmentTabs";
public static final String TAB_DADOS_CLIENTE = "dadosCliente";
public static final String TAB_DEFEITO_FALHA = "defeitoFalha";
public static final String TAB_SERVICOS = "servico";
public static final String TAB_MATERIAIS = "material";
public static final String TAB_OBSERVACAO = "observacao";
private View mRoot;
private Button enviar;
private Button cancelar;
private TabHost mTabHost;
private Ordem ordem;
private IClasseBO classeBO;
private IDispacher dispatch;
private IFragmentCo ifrag;
private int mCurrentTab;
public OrdemEncerramentoFragment(IFragmentCo ifrag, Ordem ordem) {
this.ordem = ordem;
this.ifrag = ifrag;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.ordem_encerramento, null);
enviar = (Button) mRoot.findViewById(R.ordem_encerramento.enviar);
cancelar = (Button) mRoot.findViewById(R.ordem_encerramento.cancelar);
cancelar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
OrdemEncerramentoFragment.this.dismiss();
}
});
enviar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View view = mTabHost.getChildAt(0);
new DefeitoFalhaView().getDadosDefeitoFalha(view);
}
});
mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
setupTabs();
return mRoot;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(0);
}
private void setupTabs() {
mTabHost.setup(); // importante!
mTabHost.addTab(inserirAba(TAB_DADOS_CLIENTE, R.string.tab_dados_cliente, new DadosClienteView().createView(getActivity())));
mTabHost.addTab(inserirAba(TAB_DEFEITO_FALHA, R.string.tab_defeito_falha, new DefeitoFalhaView().createView(getActivity())));
mTabHost.addTab(inserirAba(TAB_SERVICOS, R.string.tab_servico, new ServicoView().createView(getActivity())));
mTabHost.addTab(inserirAba(TAB_MATERIAIS, R.string.tab_material, new MaterialView().createView(getActivity())));
mTabHost.addTab(inserirAba(TAB_OBSERVACAO, R.string.tab_observacao, new ObservacaoView().createView(getActivity())));
}
private TabSpec inserirAba(String tag, int labelId, final View view) {
TabHost.TabSpec spec = mTabHost.newTabSpec(tag);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return(view);
}
});
spec.setIndicator(buildTabIndicator(labelId));
return spec;
}
private View buildTabIndicator(int msg) {
View indicator=LayoutInflater.from(mTabHost.getContext()).inflate(R.layout.tabs_bg_view, null);
TextView tv=(TextView)indicator.findViewById(R.id.tabsText);
tv.setText(msg);
return(indicator);
}
#Override
public void onTabChanged(String tabId) {
Log.d(TAG, "onTabChanged(): tabId=" + tabId);
}
public View getmRoot() {
return mRoot;
}
}

Taking double numbers back to previous activity

This is what i want to do with my application:
Open overview screen, go to calculator by button.
Than multiply two numbers.
By clicking calculate the intent will finish.
Outcome of multiply will be shown in first (main) activity.
I do not know how to do the last bit, someone any idea?
Code first (main) activity, OverviewpageActivity.java
package com.tip.calc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class OverviewpageActivity extends Activity {
private TextView multiplydisplay2;
private Button btntocalculator;
private double multiply = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.overview);
multiplydisplay2 = (TextView)findViewById(R.id.multiplydisplay2);
btntocalculator = (Button)findViewById(R.id.btntocalculator);
btntocalculator.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v) {
Intent intent = new Intent(OverviewpageActivity.this,
TipcalcActivity.class);
startActivity(intent);
}
});
}
}
Code calculator acticvity, TipcalcActivity.java:
package com.tip.calc;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TipcalcActivity extends Activity {
private EditText number1;
private EditText number2;
private TextView multiplydisplay;
private Button btncalculate;
private Button btnreset;
private double number1calc = 0;
private double number2calc = 0;
private double multiply = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls() {
number1 = (EditText)findViewById(R.id.number1);
number2 = (EditText)findViewById(R.id.number2);
multiplydisplay = (TextView)findViewById(R.id.multiplydisplay);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ reset(); }});
}
private void calculate() {
// check if zero
if(number1.getText().toString().trim().length() < 1 ){number1calc=0;}
else{number1calc=Double.parseDouble(number1.getText().toString());}
if(number2.getText().toString().trim().length() < 1 ){number2calc=0;}
else{number2calc=Double.parseDouble(number2.getText().toString());}
//calculate
multiply=(number1calc*number2calc);
multiplydisplay.setText(Double.toString(multiply));
finish();
}
private void reset() {
multiplydisplay.setText("");
number1.setText("");
number2.setText("");
finish();
}
}
Layout file, overview.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- multiply -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="multiply:" />
<TextView
android:id="#+id/multiplydisplay2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginLeft="20dp" />
</LinearLayout>
<Button
android:id="#+id/btntocalculator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="To the calculator" />
</LinearLayout>
Use startActivityforResult instead of startActivity in OverviewpageActivity.java and also override OnactivityResult in OverviewpageActivity.java.
Then in second activity you can set the result using setResult. Pass the intent in setresult which will have the double value.
In OnactivityResult you can get the intent from which you can extract double

Categories

Resources