how to display the number pickers in the pop up window...
I tried making the number pickers in different activity..but i want it to be displayed in a pop up window on a button click.
package com.example.uc232142.picker;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.NumberPicker;
import android.widget.PopupWindow;
import static android.app.PendingIntent.getActivity;
public class MainActivity extends AppCompatActivity {
NumberPicker numberpicker,numberPicker1,numberPicker2;
final String month[] = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};
final String sub[] ={"Airlaw","criminal","Income tax","Direct tax","Customs", "Defence & Security Forces" , "Disinvestment" , "Education" , "Election" ,
"Electricity & Energy" , "Environment, Wildlife & Animal", "Exchange Control & FDI " , "Excise"};
// TextView textview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.picker);
// final int popup=0x7f04002b;
numberpicker = (NumberPicker) findViewById(R.id.numberPicker1);
numberPicker1 = (NumberPicker) findViewById(R.id.numberPicker2);
numberPicker2 = (NumberPicker) findViewById(R.id.numberPicker3);
final ImageButton button = (ImageButton) findViewById(R.id.imageButton);
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
final View popupView = layoutInflater.inflate(R.layout.picker, null);
final PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
button.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
popupWindow.showAsDropDown(button, 10, -10);
show();
}
});
}
public void show(){
numberpicker = (NumberPicker) findViewById(R.id.numberPicker1);
numberPicker1 = (NumberPicker) findViewById(R.id.numberPicker2);
numberPicker2 = (NumberPicker) findViewById(R.id.numberPicker3);
numberpicker.setMinValue(1950);
numberpicker.setMaxValue(2018);
numberpicker.setValue(2017);
numberPicker1.setMinValue(0);
numberPicker1.setMaxValue(month.length - 1);
numberPicker1.setDisplayedValues(month);
numberPicker1.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
numberPicker2.setMinValue(0);
numberPicker2.setMaxValue(sub.length - 1);
numberPicker2.setDisplayedValues(sub);
numberPicker2.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
}
}
I've tried using AlertDialog instead of PopupWindow. It's working fine on my side, give it a try if it's what you are looking for.
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
public class MainActivity extends AppCompatActivity {
final String month[] = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};
final String sub[] ={"Airlaw","criminal","Income tax","Direct tax","Customs", "Defence & Security Forces" , "Disinvestment" , "Education" , "Election" ,
"Electricity & Energy" , "Environment, Wildlife & Animal", "Exchange Control & FDI " , "Excise"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageButton button = (ImageButton) findViewById(R.id.imageButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openDialog();
}
});
}
/**
* This will construct An {#link AlertDialog} with some custom views.
*/
private void openDialog() {
//Inflating a LinearLayout dynamically to add TextInputLayout
//This will be added in AlertDialog
final LinearLayout linearLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.view_number_dialog, null);
NumberPicker numberpicker = (NumberPicker) linearLayout.findViewById(R.id.numberPicker1);
NumberPicker numberPicker1 = (NumberPicker) linearLayout.findViewById(R.id.numberPicker2);
NumberPicker numberPicker2 = (NumberPicker) linearLayout.findViewById(R.id.numberPicker3);
numberpicker.setMinValue(1950);
numberpicker.setMaxValue(2018);
numberpicker.setValue(2017);
numberPicker1.setMinValue(0);
numberPicker1.setMaxValue(month.length - 1);
numberPicker1.setDisplayedValues(month);
numberPicker1.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
numberPicker2.setMinValue(0);
numberPicker2.setMaxValue(sub.length - 1);
numberPicker2.setDisplayedValues(sub);
numberPicker2.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
//Finally building an AlertDialog
final AlertDialog builder = new AlertDialog.Builder(this)
.setPositiveButton("Submit", null)
.setNegativeButton("Cancel", null)
.setView(linearLayout)
.setCancelable(false)
.create();
builder.show();
//Setting up OnClickListener on positive button of AlertDialog
builder.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Code on submit
}
});
}
}
view_number_dialog.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="260dp"
android:orientation="horizontal"
android:padding="14dp">
<NumberPicker
android:id="#+id/numberPicker1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<NumberPicker
android:id="#+id/numberPicker2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="14dp"
android:layout_marginRight="14dp"
android:layout_weight="1" />
<NumberPicker
android:id="#+id/numberPicker3"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
It'll output as following...
Related
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>
I am unable to find the way to create a popup like info window in map . I have to use it to show the three button inside
Yes
later
No
these three options are clickable.
The pop up will show above three button in vertical manner in recycler view . I have created recycler view and pop up view but how to show it like a Tooltip with clickabe
you can use PopupWindow, its starting with API +23
<?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="wrap_content" android:background="#FFBBFFBB" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:text="Hello My Window" android:textSize="20sp" /> <Button android:id="#+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:text="Button" android:textSize="20sp" /> </LinearLayout>
class
package com.example.hellopopupwindow;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;
public class MainActivity extends Activity {
private Context mContext = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPopupWindow(view);
}
});
}
private void showPopupWindow(View view) {
// A custom layout, as the display content
View contentView = LayoutInflater.from(mContext).inflate(
R.layout.pop_window, null);
// Set the button click event
Button button = (Button) contentView.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "button is pressed",
Toast.LENGTH_SHORT).show();
}
});
final PopupWindow popupWindow = new PopupWindow(contentView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
popupWindow.setTouchable(true);
popupWindow.setTouchInterceptor(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.i("mengdd", "onTouch : ");
return false;
// It returns true if the words, the touch event will be blocked
// PopupWindow onTouchEvent interception is not called, so click on the external area cannot be dismiss
}
});
// If you do not set the PopupWindow background, both the external region click or Back keys are not dismiss box
// I think there is a bug API
popupWindow.setBackgroundDrawable(getResources().getDrawable(
R.drawable.selectmenu_bg_downward));
// After setting the parameter to show
popupWindow.showAsDropDown(view);
}
}
I would like to create checkbox with text that would behave something like what i have below in pseudo code:
Set in text in EditText field
if Button clicked:
create new Checkbox with entered text.
How do i go about doing that in Android?
So far ive got the button :) ... but dont know how to get new Checkbox with text in it ,if its clicked
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
Button create = (Button) findViewById(R.id.button1);
create.setOnClickListener(this);
EditText textInCheckBox = (EditText) findViewById(R.id.editText1);
}
#Override
public void onClick(View v) {
// TODO Automatisch generierter Methodenstub
switch (v.getId()) {
case R.id.button1:
//after creating new checkbox with text in it
//Editbox should restet text field to null;
break;
}
}
}
Here is some code that will demonstrate how to add checkboxes dynamically with the title you entered into the EditText.
MainActivity.java
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtTitle = (EditText) findViewById(R.id.txtTitle);
final Button btnCreate = (Button) findViewById(R.id.btnCreate);
final RadioGroup radContainer = (RadioGroup) findViewById(R.id.radContainer);
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = txtTitle.getText().toString().trim();
if (!name.isEmpty()) {
CheckBox checkBox = new CheckBox(MainActivity.this);
checkBox.setText(name);
checkBox.setLayoutParams(params);
radContainer.addView(checkBox);
} else {
Toast.makeText(MainActivity.this, "Enter a title for the checkbox", Toast.LENGTH_SHORT).show();
}
}
});
}
}
activity_main.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:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp" >
<EditText
android:id="#+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone" />
<Button
android:id="#+id/btnCreate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create Checkbox" />
<RadioGroup
android:id="#+id/radContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Well, I'm testing "Dialog Fragment" and I've done a little program that when it starts show a Dialog Fragment with 3 options, the TextView on the main activity will show which option was selected. So basicly it's communication between Dialog and Activity. I was following an example with 2 buttons(positive and negative) but now I'm testing with my own layout with 3 button and I don't know how to continue...
Let's see the code:
3 Button in dialog_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3" />
</LinearLayout>
Then the DialogFragment class
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.webkit.WebView.FindListener;
import android.widget.Button;
public class TwoActionButtonsDialog extends DialogFragment {
private DialogListener listener;
public interface DialogListener {
public void onDialogOption1(DialogFragment dialog);
public void onDialogOption2(DialogFragment dialog);
public void onDialogOption3(DialogFragment dialog);
}
// Override the Fragment.onAttach() method to instantiate the
// NoticeDialogListener
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the
// host
listener = (DialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement DialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setTitle("Test").setView(
inflater.inflate(R.layout.dialog_layout, null));
Button btn1 = ((Button) findViewById(R.id.button1));
Button btn2 = (Button) findViewById(R.id.button2);
Button btn3 = (Button) findViewById(R.id.button3);
// Create the AlertDialog object and return it
return builder.create();
}
}
And the main activity
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
TwoActionButtonsDialog.DialogListener {
private static final String TAG = "dialog";
private TextView texto = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
texto = (TextView) findViewById(R.id.textView1);
showTwoActionButton();
}
public void showTwoActionButton() {
DialogFragment dialog = new TwoActionButtonsDialog();
dialog.show(getSupportFragmentManager(), TAG);
}
// The dialog fragment receives a reference to this Activity through the
// Fragment.onAttach() callback, which it uses to call the following methods
// defined by the NoticeDialogFragment.NoticeDialogListener interface
#Override
public void onDialogOption1(DialogFragment dialog) {
// User touched the dialog's positive button
texto.setText("1");
}
#Override
public void onDialogOption2(DialogFragment dialog) {
// User touched the dialog's negative button
texto.setText("2");
}
#Override
public void onDialogOption3(DialogFragment dialog) {
// TODO Auto-generated method stub
texto.setText("3");
}
}
I'm not sure how to manage the buttons beacause I can't do:
Button btn1 = ((Button) findViewById(R.id.button1));
Button btn2 = (Button) findViewById(R.id.button2);
Button btn3 = (Button) findViewById(R.id.button3);
it throws an error: "The method findViewById(int) is undefined for the type TwoActionButtonsDialog". If I've inflated the layout why I can't acces to them?
What should I do?
After you inflate your view for a Dialog, save a result:
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.dialog_layout, null)
builder.setTitle("Test").setView(v);
After that you can traverse your view for buttons:
Button btn1 = (Button) v.findViewById(R.id.button1);
I'm having a problem with my android program.
I have about every thing working what i want, but now im trying to add a password dialog.
I want to show a Dialog with a EditText(enter password) and two buttons (ok, cancel).
(working fine till so far)
When clicking on the OK button the password should be saved in mij SendData Class.
But every time I try to get the content of the EditText it gives a Java.lang NullPointerException.
Can some one help me please?
(I don't have a stack trace as i don't know where to find it :( because i'm testing on android emulator.)
If there any thing else you need, please feel free to ask.
Here is the XML-FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<requestFocus />
<EditText
android:id="#+id/txt_wachtwoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:inputType="textPassword" >
<requestFocus />
</EditText>
<Button
android:id="#+id/DialogOK"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/txt_wachtwoord"
android:layout_below="#+id/txt_wachtwoord"
android:layout_marginTop="22dp"
android:text="OK" />
<Button
android:id="#+id/Cancel"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/DialogOK"
android:layout_alignBottom="#+id/DialogOK"
android:layout_toRightOf="#+id/DialogOK"
android:text="Cancel" />
</RelativeLayout>
Here is the code:
package SebApp.Phone.Remote;
import java.net.DatagramSocket;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Vibrator;
import android.app.AlertDialog;
import android.content.DialogInterface;
public class PhoneRemote extends Activity {
private static final int VIBRATE_TIME = 100;
/** Called when the activity is first created. */
public Vibrator vibrator = null;
public sendData sd = new sendData();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
//button to call the Dialog
Button ww = (Button) findViewById(R.id.ww);
//listener password button
ww.setOnClickListener(wwOnClickListener);
}
Button.OnClickListener wwOnClickListener = new Button.OnClickListener() {
public void onClick(View v) {
try{
final EditText ww = (EditText) findViewById(R.id.txt_wachtwoord);
//set up dialog
Dialog dialog = new Dialog(PhoneRemote.this);
dialog.setContentView(R.layout.wachtwoord);
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
//there are a lot of settings, for dialog, cheout!
//set up button
Button button = (Button) dialog.findViewById(R.id.DialogOK);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try{
Toast.makeText(v.getContext(),"PWfield contains: " + ww.getText().toString(), Toast.LENGTH_SHORT).show();
//finish();
}catch(Exception e)
{
Toast.makeText(v.getContext(),e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
dialog.show();
}catch(Exception E){
Toast.makeText(v.getContext(),E.toString(), Toast.LENGTH_SHORT).show();
}
}
};
}
Button.OnClickListener wwOnClickListener = new Button.OnClickListener() {
public void onClick(View v) {
try{
final EditText ww = (EditText) findViewById(R.id.txt_wachtwoord);
//set up dialog
Dialog dialog = new Dialog(PhoneRemote.this);
dialog.setContentView(R.layout.wachtwoord);
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
....
instead use
Button.OnClickListener wwOnClickListener = new Button.OnClickListener() {
public void onClick(View v) {
try{
Dialog dialog = new Dialog(PhoneRemote.this);
dialog.setContentView(R.layout.wachtwoord);
final EditText ww = (EditText) dialog.findViewById(R.id.txt_wachtwoord);
//set up dialog
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
....
you had declared EditText before setting the dialog view
I have yet to run your code. However, I would say the variable wwOnClickListener is being initialized before the onCreate method.
Therefore the layout is not set, as the layout is set within the onCreate method. To fix this I would pull out the following
final EditText ww = (EditText) findViewById(R.id.txt_wachtwoord);
From the buttonlistener and make ww a global variable which is initialized in the onCreate method.
I would expect that will resolve the issue.