How to get the text value of a button from another layout? - android

First of all, I have searched in forum for "How to get text from edittext in other layout", and tried many other ways, then I decided to use LayoutInflater but it did not help.
The implementation of LayoutInflater (I follow this guide)
LayoutInflater factory = getLayoutInflater();
View regisText = factory.inflate(R.layout.regis, null);
EditText user = (EditText) regisText.findViewById(R.id.edt1);
String usr = user.getText().toString();
My parent layout is named activity_input.xml having 3 buttons (I do not set text button). I put only button Id for easy view.
<Button
android:id="#+id/btn1">
</Button>
<Button
android:id="#+id/btn2">
</Button>
<Button
android:id="#+id/btn3">
</Button>
After I click a button, one dialog appears to select value (1, 2 or 3) to set the button display text (1, 2 or 3) in activity_input.xml.
final Dialog dialog1 = new Dialog(user_input.this);
dialog1.setTitle("Select a Number");
dialog1.setContentView(R.layout.game_dialog);
dialog1.show();
button1 = (Button) dialog1.findViewById(R.id.btn1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Button p1_btn = (Button) findViewById(x);
p1_btn.setText("1");
dialog1.dismiss();
}
});
The onClick works perfect.
But my problem is that I want to get the text of the button in parent layout again, I try to implement Layoutinflater but it does not work, here is the code.
LayoutInflater f1 = getLayoutInflater();
View v1 = f1.inflate(R.layout.activity_input, null);
Button btn1 = (Button) v1.findViewById(R.id.b1);
String t1 = btn1.getText().toString();
I check to make sure that the String t1 is retrieve successfully by print the string but it shows nothing
Hope you guide help me as soon as possible!
Thanks you very much.

You can make a static variable and store the result there, then access it from your dialog. So in your ActivityInput.java
public class ActivityInput extends Activity {
public static String input = "";
//code
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Button p1_btn = (Button) findViewById(x);
input = "1";
p1_btn.setText(input);
dialog1.dismiss();
}
});
}
Now in your other java class ActivityOutput.java:
public class ActivityOutput extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
//code
String result = ActivityInput.input;
//use the result string somewhere to display it in your app
}
}

Related

EditText in dialog returning null string

I have this button to show a dialog which in turn has an EditText for the users to write something and then tap the done button to save it otherwise another button to close the dialog. The problem here is that I am not able to fetch that String that the user wrote. It returns me a null sting instead and causes the app to crash. Here's the code :
I call the dialog up on clicking on a button:
//Write Review Dialog Box
writeReviewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("HAPPENED", "This Onclick is working");
try{
// Create custom dialog object
final Dialog dialog = new Dialog(GetReviewActivity.this);
// Include dialog's xml file
dialog.setContentView(R.layout.write_review_activity);
// Set dialog title
dialog.setTitle("Your review is valuable");
final EditText etWR = (EditText)findViewById(R.id.etWR);
Button writeButton = (Button) dialog.findViewById(R.id.buttonWR);
Button declineButton = (Button) dialog.findViewById(R.id.buttonNoThanks);
dialog.show();
//Done Button
writeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("HAPPENED: ","writeButton Block Is WORKING!");
Activity activity = GetReviewActivity.this;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
String Review = etWR.getText().toString();
StoreAReview(Review);
}
});
}
});
// if decline button is clicked, close the custom dialog
declineButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
});
final EditText etWR = (EditText)findViewById(R.id.etWR); is resolving to Activity#findViewById. But your dialog's layout is not attached to your activity window, it's attached to the dialog. so you have to inflate EditText from your dialog's view:
Try
final EditText etWR = (EditText)dialog.findViewById(R.id.etWR);
instead of
final EditText etWR = (EditText)findViewById(R.id.etWR);
Been through this issue before. I tried initiating EditText with Dialog reference but this didn't work
final EditText etWR = (EditText)dialog.findViewById(R.id.etWR);
Solution:
This is how I solved it:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View dialogWR = getActivity().getLayoutInflater().inflate(R.layout.write_review_activity, null);
etWR = (EditText) dialogWR.findViewById(R.id.etWR);
}
You should initialize EditText
EditText etWR = (EditText)dailog.findViewById(R.id.etWR);
becoz your EditText is coming from dailog. So
U just miss the dialog.findViewById(R.id.etWR)
change this line
final EditText etWR = (EditText)findViewById(R.id.etWR);
to this one
final EditText etWR = (EditText)dialog.findViewById(R.id.etWR);
then, add click event code

Use a button to add other buttons, editText etc.

I need to be able to add buttons to a layout using an "add" button. The problem is that I need each button to have an OnClickListener()/onClick method. I was thinking every time the "add" button is pressed then i would add a new button to an array but im not sure add the listener and implement an onClick method for each button I create.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SmartChronometer chrono = (SmartChronometer) findViewById(R.id.chrono);
final Button start = (Button) findViewById(R.id.button2);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (chrono.isRunning())
chrono.pause();
else {
chrono.chronoStart();
}
}
});
}
I need to add chronomoter,button and listeners every time I click an "Add" button.
set all the clicklisteners as you wich!
call findViewById(R.id.btnSecond).setVisibility(View.GONE); on creat, then when clickin the first button
Button btnSecond;
...
public void onClick(View v) {
findViewById(R.id.btnSecond).setVisibility(View.VISIBLE);
if (btnSecond.getVisibility() == View.VISIBLE); {
findViewById(R.id.btnThird).setVisibility(View.VISIBLE);}
}
this way you can put all your information in the java file and all buttons in xml, but they will be hidden until click.
This is one way, other answer my come. Good Luck :)
implements OnClickListener
Button add = (Button) findViewById (R.id.addButton);
add.setOnClickListener (this);
List<Button> buttons = new ArrayList <Button>();
for (int i = 0; i < buttons.size (); i++){
buttons.get (i).setOnClickListener (this);
}
#Override
public void onClick (View v){
for (int i = 0; i < buttons.size (); i++){
if (v.getId () == buttons.get (i).getId ()){
// do stuff you want
}else if (v.getId() == R.id.addButton){
//add button
}
}
}
Hope this will work, didnt test it.

how do call another class in android?

I have a problem. I do not know how to call a different class. the code is for a button (when you click the button a message appears in random) so i thought it would be better if i placed it in a different class as i have also used arrays.Now i do not know how to call the class.
This is my code.I want to call "Firstin" inside SecondActivity.
public class SecondActivity extends Activity {
private Firstin mFirst = new Firstin ();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//finds textview
final Text Ftext = (Text) findViewById(R.id.textView2);
#SuppressWarnings("unused")
final Text Stext = (Text) findViewById(R.id.textView3);
//finds button view
Button btnView = (Button) findViewById(R.id.button1);
#SuppressWarnings("unused")
Button btnView2 = (Button) findViewById(R.id.button2);
btnView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String Answer = mFirst.firstAnswer();
Ftext.setTextContent(Answer);
}
});
this is the class I'm trying to call:
package com.example.insultgenerator;
import java.util.Random;
public class Firstin {
public String firstAnswer(){
String [] mResults={
"its cool",
"we cool",
"im cool",
"he cool",
"she cool"
};
// the button was clicked so replace the answer label with answer
String Answer = "" ;
// the two double is a 'empty string
Random RandomGen = new Random();// telling the program to construct a random generator
int RandomNum= RandomGen.nextInt(mResults.length);
Answer = mResults[RandomNum];
return(Answer);
}
}
You should cast to TextView
final TextViewFtext = (TextView) findViewById(R.id.textView2);
#SuppressWarnings("unused")
final TextViewStext = (TextView) findViewById(R.id.textView3);
then use TextView.setText(...) method:
String Answer = mFirst.firstAnswer();
Ftext.setText(new Firstin().firstAnswer());
}
});
then last call the method from the other class with new Firstin().firstAnswer() which creates a instance of the class and executes the method.

Dialog still show after click positive button

I have button on (CustomDilaog activity) when clicked show custom dialog with password edittext and OK button and cancel button , if you put correct password it open another activity (Text activity), till now every things work fine ,
i have question with two parts.
Part one : when im in (Text activity) and press back button to return to (CustomDilaog activity) , still the dialog show over it , how to let it dismiss
Part two : after dialog fired , if i dont write password and just click OK button with edittext empty it has no response , how to let this click just dismiss dialog without no action ( which is open (Text activity) if wrote correct password .
(CustomDilaog activity):
public class CustomDilaog extends Activity {
final Context context = this;
private Button button;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv=(TextView)findViewById(R.id.introclusion_tv1);
tv.setTypeface(FontFactory.getBFantezy(getBaseContext()));
TextView tv1=(TextView)findViewById(R.id.introclusion_tv2);
tv1.setTypeface(FontFactory.getBFantezy(getBaseContext()));
tv1.setText(Html.fromHtml(getString(R.string.introclusion)));
button = (Button) findViewById(R.id.button1);
// add button listener
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// custom dialog
final Dialog dialog = new Dialog(context,R.style.cust_dialog);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom);
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text);
Typeface font = Typeface.createFromAsset(getAssets(), "BFantezy.ttf");
text.setTypeface(font);
text.setText("write password :");
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
Typeface font1 = Typeface.createFromAsset(getAssets(), "BFantezy.ttf");
dialogButton.setTypeface(font1);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText password = (EditText) dialog.findViewById(R.id.password);
////
if( password.getText().toString().length() > 0 ) {
if( password.getText().toString().equals("test")) {
Intent intent = new Intent(CustomDilaog.this,Text.class);
startActivity(intent);
}
else{
// get your custom_toast.xml layout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast));
// set a dummy image
ImageView image = (ImageView) layout.findViewById(R.id.image_toast);
image.setImageResource(R.drawable.ic_launcher);
// set a message
TextView text = (TextView) layout.findViewById(R.id.text_toast);
text.setText("Wrong password");
// Toast...
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
}
}
});
Button dialogButtonCancell = (Button) dialog.findViewById(R.id.cancel);
Typeface font11 = Typeface.createFromAsset(getAssets(), "BFantezy.ttf");
dialogButtonCancell.setTypeface(font11);
dialogButtonCancell.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
}
call dialog.dismiss() at the beginning of dialogButton click listener:
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
EditText password = (EditText) dialog.findViewById(R.id.password);
if( password.getText().toString().length() > 0 ) {
...
}
});
Part one : when im in (Text activity) and press back button to return to (CustomDilaog activity) , still the dialog show over it , how to let it dismiss
Simply call finish() in your CustomDialogActivity when you start the new Activity. It looks like your Intent is calling this same Activity though so I'm a little confused on that.
if( password.getText().toString().length() > 0 ) {
if( password.getText().toString().equals("test")) {
Intent intent = new Intent(CustomDilaog.this,Text.class);
startActivity(intent);
Part two : after dialog fired , if i dont write password and just click OK button with edittext empty it has no response , how to let this click just dismiss dialog without no action ( which is open (Text activity) if wrote correct password .
Add an else statement to your first if and inside it put dialog.dismiss()

PopupWindow not triggering sytem context dialog on EditText long-press

Sorry if the title was a bit vague.
I'm developing an app on Freelancer and I almost have it finished except for a complaint from the customer after some testing.
I use a PopupWindow in place of a dialog to edit contextual settings, if that makes any sense. I don't want to be too specific and risk giving the app concept away, which I'm sure the customer wouldn't be too pleased about.
The PopupWindow is given a Content View of a layout inflated from XML. In that layout are several EditText widgets. The issue is that those EditTexts will not trigger the default contextual dialog on long press that presents options for text/IME selection, and cut/copy/paste.
I saw a similar question trying to get the TouchTrigger or something and it not working without setBackgroundDrawable(), which I've tried with a simple new ColorDrawable(). It still doesn't work.
Is there any easy way to trigger the system-default long-press dialog in an OnLongPressListener, or will I have to move Heaven and Earth to implement it myself? Because if that's the case, I'll just write a Fragment for it and swap it out in a transaction. I know that'll work.
The relevant code:
Inside the initiating fragment:
RulesDialog dialog;
PopupWindow window;
public void showAddRuleDialog(){
dialog = new RulesDialog();
View view = getView();
window = new PopupWindow(dialog.initViews(this, null), view.getWidth(), view.getHeight(), true);
window.setBackgroundDrawable(new ColorDrawable());
dialog.setRulesDialogListener(new rulesDialogListener(){
#Override
public void onSave(ViewHolder holder) {
addRule(holder);
window.dismiss();
}
#Override
public void onCancel() {
window.dismiss();
}});
int[] location = {0,0};
view.getLocationOnScreen(location);
window.showAtLocation(view, 0, location[0], location[1]);
In RulesDialog:
public class ViewHolder{
public ViewHolder(View dialogView){
name = (TextView) dialogView.findViewById(R.id.name);
response = (TextView) dialogView.findViewById(R.id.response);
senders = (TextView) dialogView.findViewById(R.id.senders);
sendersAdd = (Button) dialogView.findViewById(R.id.sendersAdd);
sendersEdit = (Button) dialogView.findViewById(R.id.sendersEdit);
timeFrom = (TextView) dialogView.findViewById(R.id.from);
timeFromEdit = (Button) dialogView.findViewById(R.id.timeBeforeEdit);
timeTo = (TextView) dialogView.findViewById(R.id.to);
timeToEdit = (Button) dialogView.findViewById(R.id.timeAfterEdit);
keywords = (TextView) dialogView.findViewById(R.id.keywords);
matchCase = (CheckBox) dialogView.findViewById(R.id.matchCase);
matchAlone = (CheckBox) dialogView.findViewById(R.id.matchAlone);
matchPlural = (CheckBox) dialogView.findViewById(R.id.matchPlural);
cancel = (Button) dialogView.findViewById(R.id.cancel);
save = (Button) dialogView.findViewById(R.id.save);
}
TextView name;
TextView response;
TextView senders;
Button sendersAdd;
Button sendersEdit;
TextView timeFrom;
Button timeFromEdit;
TextView timeTo;
Button timeToEdit;
TextView keywords;
CheckBox matchCase;
CheckBox matchAlone;
CheckBox matchPlural;
Button cancel;
Button save;
}
Activity activity;
ViewHolder holder;
Fragment fragment;
public View initViews(Fragment mFragment, Rule rule){
fragment = mFragment;
activity = fragment.getActivity();
View dialogView = LayoutInflater.from(activity).inflate(R.layout.rules_dialog, null);
holder = new ViewHolder(dialogView);
final TextView senders = holder.senders;
holder.sendersAdd.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
showContacts();
}});
holder.sendersEdit.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
editSenders(senders);
}
});
final TextView timeFrom = holder.timeFrom;
holder.timeFromEdit.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
showTimePickerDialog(timeFrom);
}
});
final TextView timeTo = holder.timeTo;
holder.timeToEdit.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
showTimePickerDialog(timeTo);
}
});
holder.cancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
mListener.onCancel();
}});
holder.save.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
mListener.onSave(holder);
}});
if(rule == null)
rule = new Rule();
holder.name.setText(rule.name);
holder.response.setText(rule.response);
holder.senders.setText(rule.senders.toString());
holder.senders.setTag(rule.senders);
holder.keywords.setText(rule.keywords);
holder.matchCase.setChecked(rule.matchCase);
holder.matchAlone.setChecked(rule.matchAlone);
holder.matchPlural.setChecked(rule.matchPlural);
holder.timeFrom.setTag(rule.timeFrom);
holder.timeFrom.setText(Rules.formatTime(rule.timeFrom));
holder.timeTo.setTag(rule.timeTo);
holder.timeTo.setText(Rules.formatTime(rule.timeTo));
return dialogView;
}
So I tried rewriting RulesDialog as a fragment, and it didn't work out too well. Had issues with making Fragment Transactions work right when called from the Fragments they're operating on.
(I know this isn't the point to fragments. I'm not really aiming to write a completely modular app right now. I just want to come out with a product the customer will be happy with.)
I ended up rewriting RulesDialog as an Activity instead, and using startActivityForResult() from the calling fragment. Then passing the edited data back with setResult(). It all works nicely in concert.

Categories

Resources