Adding EditText with button click - javascript

EBelow is my code for adding EditText to my layout and it works fine but I want it to create the new EditText boxes below the ones that was created. If you see something in the code I should change or improve, pls comment.Thanks in advance.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_weight_log);
relativeLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
tt= (EditText)findViewById(R.id.tt);
dd = (EditText)findViewById(R.id.dd);
aa = (Button) findViewById(R.id.add);
aa.setOnClickListener(new Button.OnClickListener()
{public void onClick
(View v) { aa();}});
}
public void aa()
{ for(i = 0; i <100; ++i);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relativeLayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams (
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.BELOW);
params.setMargins(0,600,0,0);
EditText edtTxt = new EditText(this);
int maxLength = 5;
edtTxt.setHint("editText1");
edtTxt.setLayoutParams(params);
edtTxt.setBackgroundColor(Color.WHITE);
edtTxt.setInputType(InputType.TYPE_CLASS_DATETIME);
edtTxt.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(maxLength);
edtTxt.setFilters(fArray);
layout.addView(edtTxt);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params1.setMargins(0,600,0,0);
EditText editText = new EditText(this);
int maxLength1 = 4;
editText.setHint("editText2");
editText.setLayoutParams(params1);
editText.setBackgroundColor(Color.WHITE);
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
editText.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
fArray[0] = new InputFilter.LengthFilter(maxLength1);
editText.setFilters(fArray);
layout.addView(editText);
}

Try changing to linear layout and setting its orientation to vertical. Then if you will add a new view it will be added below your previous view.

Related

How do you create multiple dropdown boxes in Java? I want to add another drop down box after these lines of code

JFrame frame = new JFrame("Recipes");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocation(430, 100);
JPanel panel = new JPanel();
frame.add(panel);
JLabel lbl = new JLabel("Select time taken");
lbl.setVisible(true);
panel.add(lbl);
String[] choices = { "10 MINS","15 MINS", "20 MINS","25 MINS","30 MINS"};
final JComboBox<String> cb = new JComboBox<String>(choices);
cb.setVisible(true);
panel.add(cb);
JButton btn = new JButton("OK");
panel.add(btn);`
I don't know what to add after this, I tried adding another label and combobox but it didn't work
Ensure that frame.setVisible(true); is in the last line
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame("Recipes");
//frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocation(430, 100);
JPanel panel = new JPanel();
frame.add(panel);
JLabel lbl = new JLabel("Select time taken");
lbl.setVisible(true);
panel.add(lbl);
String[] choices = { "10 MINS","15 MINS", "20 MINS","25 MINS","30 MINS"};
final JComboBox<String> cb = new JComboBox<String>(choices);
cb.setVisible(true);
panel.add(cb);
JButton btn = new JButton("OK");
panel.add(btn);
frame.setVisible(true);
}
}

Fragment to activity and go back to the fragment

how can i intent back from (activity1-> fragment1) actually my design concept is like ( fragment1-> activity1-> fragment1) in fragment1 i click the data it bring me to activity1 for edit purpose or either update the data or remove the data after click either both button it will bring me back to the fragment1 and look the overall data but my problem is i click either both button it will jump out from the app, how can i solve this problem? using intent or ?
the code below is Update_detail_info ( activity1 )
public class Update_detail_info extends AppCompatActivity implements View.OnClickListener {
EditText weight,bodyf,timef,datef,commentf;
Button btnUpdate, btnRemove;
long weight_id;
SQLControlerWeight dbcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_detail_info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbcon = new SQLControlerWeight(this);
dbcon.openDatabase();
btnUpdate = (Button) findViewById(R.id.button_update);
btnRemove = (Button) findViewById(R.id.button_remove);
Intent i = getIntent();
String weightID = i.getStringExtra("weightId");
String dN = i.getStringExtra("dateNum");
String tN = i.getStringExtra("timeNum");
String wN = i.getStringExtra("weightNum");
String bN = i.getStringExtra("bodyFatNum");
String cM = i.getStringExtra("comment");
weight_id = Long.parseLong(weightID);
datef.setText(dN);
timef.setText(tN);
weight.setText(wN);
bodyf.setText(bN);
commentf.setText(cM);
btnUpdate.setOnClickListener(this);
btnRemove.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_update:
String d_update = datef.getText().toString();
String t_update = timef.getText().toString();
String w_update = weight.getText().toString();
String b_update = bodyf.getText().toString();
String c_update = commentf.getText().toString();
dbcon.updateNote(weight_id,w_update,b_update,d_update,t_update,c_update);
this.returnHome();
break;
case R.id.button_remove:
dbcon.deleteNote(weight_id);
this.returnHome();
break;
}
}
public void returnHome() { // is that here the code are wrong ? cause i need to jump back to the previous fragment1
Intent home_intent = new Intent(getApplicationContext(),
HistoryF.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home_intent);
}
}
break;
}
code below is the fragment for HistoryF ( fragment1)
public class HistoryF extends Fragment {
View contentView;
ListView list;
SQLControlerWeight dbconnection;
TextView weight_num, date_num, time_num, bf_num, comment,weight_ID;
private SimpleCursorAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
contentView = inflater.inflate(R.layout.history_fragment, container, false);
dbconnection = new SQLControlerWeight(getActivity());
dbconnection.openDatabase();
list = (ListView) contentView.findViewById(R.id.listViewWeight);
Cursor cursor = dbconnection.readNote();
String[] from = new String[]{
DBHelperNote.WEIGHT_ID,
DBHelperNote.WEIGHT_NUM,
DBHelperNote.BODY_FAT,
DBHelperNote.WEIGHT_DATE,
DBHelperNote.WEIGHT_TIME,
DBHelperNote.WEIGHT_COMMENTS
};
int[] to = new int[]{
R.id.weight_id,
R.id.weight_num,
R.id.bf_num,
R.id.date_num,
R.id.time_num,
R.id.comment_text
};
adapter = new SimpleCursorAdapter(
contentView.getContext(), R.layout.history, cursor, from, to,0);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
weight_ID = (TextView) view.findViewById(R.id.weight_id);
weight_num = (TextView) view.findViewById(R.id.weight_num);
bf_num = (TextView) view.findViewById(R.id.bf_num);
date_num = (TextView) view.findViewById(R.id.date_num);
time_num = (TextView) view.findViewById(R.id.time_num);
comment = (TextView) view.findViewById(R.id.comment_text);
String weightId = weight_ID.getText().toString();
String wn = weight_num.getText().toString();
String bfn = bf_num.getText().toString();
String dn = date_num.getText().toString();
String tn = time_num.getText().toString();
String cm = comment.getText().toString();
Intent modify_intent = new Intent(getActivity(), Update_detail_info.class);
modify_intent.putExtra("weightId", weightId);
modify_intent.putExtra("dateNum", dn);
modify_intent.putExtra("timeNum", tn);
modify_intent.putExtra("weightNum", wn);
modify_intent.putExtra("bodyFatNum", bfn);
modify_intent.putExtra("comment", cm);
startActivity(modify_intent);
}
});
return contentView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
this is my main activity for control the tab
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new KeyInWeightF(), "TRACK");
adapter.addFragment(new HistoryF(), "HISTORY");
adapter.addFragment(new AnalysisF(), "GRAPH");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can simply use this code on your returnHome()
Intent intent = NavUtils.getParentActivityIntent(Update_detail_info.this); //get parent activity
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(Update_detail_info.this, intent); // and then navigate it to parent
or
NavUtils.navigateUpFromSameTask(Update_detail_info.this);
both worked same
and in your manifest file define parentActivity
manifest.xml
<activity
android:name="com.example.yourApp.MainActivity" ...>
...
</activity>
<!-- A child of the main activity -->
<activity
android:name="com.example.yourApp.Update_detail_info"
android:label="#string/title_activity_Update_detail"
android:parentActivityName="com.example.yourApp.MainActivity" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.yourApp.MainActivity" />
</activity>
For more details to Providing Up Navigation go to this link.
And for understand startactivityforresult go to this link

Listview containing checkbox and text is getting reset on scrolling

I have drawn a customized navigation drawer with ListView and header but when i scroll the List the checkbox in the List are getting unchecked.
Secondly when i click on the reset button in the header part I want that all the checkbox in the Listview should get get unchecked. I have been trying this to get it working but unable to find any solution..
The snippets are
public class NavigationDrawer extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.filter_navigation_drawer, container,false);
drawerListView= ( ListView ) view.findViewById( R.id.listDrawer );
drawerListView.setOnItemClickListener(new FilterDrawerItemClickListener());
dataList.add(new FilterDrawerItem("sample1",true));
dataList.add(new FilterDrawerItem("sample2",true));
dataList.add(new FilterDrawerItem("sample3",true));
dataList.add(new FilterDrawerItem("sample4",true));
dataList.add(new FilterDrawerItem("sample5",true));
dataList.add(new FilterDrawerItem("sample2",true));
dataList.add(new FilterDrawerItem("sample2",true));
dataList.add(new FilterDrawerItem("sample2",true));
dataList.add(new FilterDrawerItem("sample2",true));
adapter = new FilterCustomDrawerAdapter(getActivity(), R.layout.drawer_filter,dataList,drawerStatus);
drawerListView.setAdapter(adapter);
adapter.getFilterList();
resetBtn = (TextView)view.findViewById(R.id.filterby_reset);
if(resetBtn != null){
resetBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
application.setFilterStatus("reset");
for(int i=0; i<dataList.size(); i++){
dataList.get(i).setCheckBoxId(false);
}
adapter.notifyDataSetChanged();
// this.onCreateView();
}
});
}
return view;
}
}
FilterCustomDrawerAdapter.java
public class FilterCustomDrawerAdapter extends ArrayAdapter<FilterDrawerItem> {
Context context;
List<FilterDrawerItem> drawerItemList;
int layoutResID;
int item = 0;
String status;
List<Integer> filterList = new ArrayList<Integer>();
DrawerStatus drawerStatus;
StataApplication application = StataApplication.getInstance();
HashMap<Integer, Boolean> checked; // newly added code
public FilterCustomDrawerAdapter(Context context, int layoutResourceID,
List<FilterDrawerItem> listItems,DrawerStatus drawerStatus) {
super(context, layoutResourceID, listItems);
this.context = context;
this.drawerItemList = listItems;
this.layoutResID = layoutResourceID;
this.drawerStatus = drawerStatus;
checked = new HashMap<Integer, Boolean>(getCount());
}
public FilterCustomDrawerAdapter(Context context, int layoutResourceID,
List<FilterDrawerItem> listItems) {
super(context, layoutResourceID, listItems);
this.context = context;
this.drawerItemList = listItems;
this.layoutResID = layoutResourceID;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final FilterDrawerItemHolder drawerHolder;
View view = convertView;
if (view == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
drawerHolder = new FilterDrawerItemHolder();
view = inflater.inflate(layoutResID, parent, false);
drawerHolder.ItemName = (TextView) view.findViewById(R.id.drawer_filterName);
drawerHolder.checkBox = (CheckBox) view.findViewById(R.id.drawer_cbox);
view.setTag(drawerHolder);
} else {
drawerHolder = (FilterDrawerItemHolder) view.getTag();
}
FilterDrawerItem dItem = (FilterDrawerItem) this.drawerItemList.get(position);
drawerHolder.ItemName.setText(dItem.getItemName());
TextView resetView = (TextView)view.findViewById(R.id.filterby_reset);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.drawer_cbox);
// Newly added code
Boolean isChecked = checked.get(position);
checkBox.setChecked(isChecked == null ? false : isChecked);
// if(application.getFilterStatus() != null) {
if(checkBox.isChecked()){
drawerHolder.checkBox.setChecked(false);
}
// }
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if (isChecked) {
filterList.add(new Integer(position));
checked.put(position, true);
} else {
filterList.remove(new Integer(position));
checked.put(position, false);
}
}
});
drawerHolder.checkBox.setTag(position);
Log.d("FILTER_LIST_SIZE",String.valueOf(filterList.size()));
return view;
}
private static class FilterDrawerItemHolder {
TextView ItemName;
CheckBox checkBox;
}
public List<Integer> getFilterList(){
return filterList;
}
}
In the image below when I scroll the list and if i make the checkbox sample1 and sample 2 checked it becomes unchecked on scrolling.
and also on clicking reset button in the header i want all my checkbox to be unchecked..
Not able to get this working ...
UPDATE 1
resetBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<FilterDrawerItem> adapterDataList = adapter.getDrawerItemList();
for(int i=0; i<adapterDataList.size(); i++){ // At this place i am getting the size as 9
adapterDataList.get(i).setCheckBoxId(false);
}
adapter.setDrawerItemList(adapterDataList);
adapter.notifyDataSetChanged();
}
});
In your FilterDrawerItem class, make a boolean variable isChecked.
Now in your adapter class, write something like this:
if(dItem.isChecked){
drawerHolder.checkBox.setChecked(true);
}
else{
drawerHolder.checkBox.setChecked(false);
}
and in your OnCheckedChangeListener:
if (isChecked) {
//your other code
dItem.setChecked(true);
notifyDataSetChanged();
} else {
//your other code
dItem.setChecked(false);
notifyDataSetChanged();
}
#Orest Savchak's answer is also right, but keeping track of checkboxes in your POJO classes will help you to retrieve the checked items later and also do other things easier, like you want to uncheck all the checkboxes on click of "Reset" button. For that, in onClick() on reset button, you'll just need to do:
for(int i=0; i<FilterDrawerItem.size; i++){
FilterDrawerItem.get(i).setChecked(false);
}
adapterObject.notifyDataSetChanged();
EDIT 1:
Create getter setter for drawerItemList in your adapter and then in onClick() of reset button, in place of dataList, do as following:
List<FilterDrawerItem> adapterDataList=adapter.getDataList();
for(int i=0; i<adapterDataList.size(); i++){
adapterDataList.get(i).setCheckBoxId(false);
}
adapter.setDataList(adapterDataList);
adapter.notifyDataSetChanged();
It because of recycling use of views in ListView. You should create some HashMap:
HashMap<Integer, Boolean> checked;
Then in your constructor do this:
checked = new HashMap<Integer, Boolean>(getCount());
After set OnCheckedChangeListener on your checkboxes, and in event method do this:
checked.put(position, yourCheckBoxCheckedState);
And in getView() method do this:
Boolean isChecked = checked.get(position);
checkBox.setChecked(isChecked == null ? false : isChecked)
Try this, I think it should help
UPDATE
resetBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.deselectAll();
}
});
Then in adapter create method:
public void deselectAll() {
checked = new HashMap<Integer, Boolean>(getCount());
notifyDataSetChanged();
}

Calling Web Method using Javascript on dynamically created Control

I am creating some controls dynamically in these Dynamic control there is <asp: Image> Control
I want to call webmethod when I click that Image control.I searched a lot but nothing is happening.
the code for Dynamic control is
for (int i = 0; i < SearchResult.Length; i++)
{
System.Web.UI.HtmlControls.HtmlGenericControl panel = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
panel.Attributes["class"] = "panel";
panel.ID = "panel_" + (i + 1).ToString();
System.Web.UI.HtmlControls.HtmlGenericControl inside = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
inside.Attributes["class"] = "inside";
Image img = new Image();
img.ImageUrl = SearchResult[i].ImageUrl;
// img.Attributes.Add("onclick", THE WEB Method I want to call);
inside.Controls.Add(img);
Label label = new Label();
label.Text = SearchResult[i].Title;
label.Font.Size = 10;
label.Font.Bold = true;
panel.Controls.Add(label);
panel.Controls.Add(inside);
test.Controls.Add(panel);
}
and my web method is
[WebMethod]
public static void AddToDownload(String ConnectionString,String Query)
{
SqlConnection con = new SqlConnection(ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
cmd.ExecuteNonQuery();
con.Close();
}
Get rid of the "onclick" line and wire up a server-side Click event, like this:
protected void Page_Load(object sender, EventArgs e)
{
var img1 = new ImageButton
{
ID = "ImageButton1",
AlternateText = "Button 1"
};
img1.Click += img_Click;
Panel1.Controls.Add(img1);
var img2 = new ImageButton
{
ID = "ImageButton2",
AlternateText = "Button 2"
};
img2.Click += img_Click;
Panel1.Controls.Add(img2);
}
private void img_Click(object sender, ImageClickEventArgs e)
{
var whoClicked = (sender as ImageButton).ID;
}
I have changed your Image server controls to ImageButton server controls to more easily accommodate the Click event.
Each of the two buttons is wired up to a common event handler and then in the event handler it is casting the sender (the control that initiated the event) to an ImageButton and then grabbing its ID to distinguish between the two buttons. You would want to put a null check there in case something besides an ImageButton initiates a click event.
Let me know if you need anything clarified or have further questions.

Display android DatePicker on click of a button in Javascript

Here is my requirement :
I'am loading one html file on to a WebView. I have a button in html file to select the date. When i click on that button i want to open android date picker dialog. And after selecting the date, i want to display the selected date in html file. Can anyone guide me. please.
HTML :
<input type="button" value="Select Date" onClick="openDatePickerDialog()" />
<p id = "date">--</p>
Javascript :
function openDatePickerDialog() {
AndroidFunction.openDatePickerDialog();
}
function callFromActivity(date) {
document.getElementById('date').innerHTML = date;
}
My Activity :
public class MainActivity extends Activity {
WebView myBrowser;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myBrowser = (WebView)findViewById(R.id.mybrowser);
final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this);
myBrowser.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
myBrowser.getSettings().setJavaScriptEnabled(true);
myBrowser.loadUrl("file:///android_asset/test.html");
}
public class MyJavaScriptInterface
{
private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 0;
Context mContext;
MyJavaScriptInterface(Context c)
{
mContext = c;
}
public void openDatePickerDialog()
{
Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
//updateDisplay();
showDialog(DATE_DIALOG_ID);
}
private void updateDisplay() {
String date = new StringBuilder().append(mMonth + 1).append("-")
.append(mDay).append("-")
.append(mYear).append(" ").toString();
Toast.makeText(getApplicationContext(), date, Toast.LENGTH_LONG).show();
myBrowser.loadUrl("javascript:callFromActivity(\""+date+"\")");
}
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(MainActivity.this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
}
}
Problem : I'am not getting DatePicker Dialog When i click on button. Where i'am going wrong ? Is my approach correct ?
Here is a sample code I use do show, derived from the code here:
In the html code, add 2 javascript functions:
// Fonction d'appel calendrier Android
function f_CallCalendar(Tag)
{
MSSAndroidFunction.openDatePickerDialog(Tag);
}
// Fonction de retour de la date
function callFromActivity_RetDate(Tag, data) {
document.Form.vDate.value = data;
}
The Tag is the id of the input form to be completed. You call the javascript functions like this:
<input name="vDate" type="text" size="11" />
<input name="Submit" type="button" onclick="f_CallCalendar('vDate')" value="Calendrier*" />
And here is the java code implemented. Note that the MyJavaScriptInterface is declared inside the MainActivity:
public class MainActivity extends Activity
implements TextWatcher{
WebView MainWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainWebView = (WebView)findViewById(R.id.main_webview);
MainWebView.getSettings().setJavaScriptEnabled(true);
final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this);
MainWebView.addJavascriptInterface(myJavaScriptInterface, "MyJavaScriptInterface");
}
// Classe de prise en charge du java privé
public class MyJavaScriptInterface
{
public String m_szTagId;
Context mContext;
MyJavaScriptInterface(Context c)
{
mContext = c;
}
public void openDatePickerDialog(String szTagId)
{
m_szTagId = szTagId;
Calendar c = Calendar.getInstance();
DatePickerDialog dp = new DatePickerDialog(mContext, new OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
String szDate = String.format("%02d/%02d/%04d", dayOfMonth, monthOfYear+1, year);
MainWebView.loadUrl("javascript:callFromActivity_RetDate(\""+m_szTagId+"\", \""+szDate+"\")");
} }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
dp.show();
}
} // Class MyJavaScriptInterface
} // class MainActivity
Here is it. Hope this can help.
public void openDatePickerDialog()
{
Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
//updateDisplay();
DatePickerDialog dp = new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
dp.show();
}
can you try this once.

Categories

Resources