正在发生的事情是在一个标签页面中,我将列表视图中的项目添加到单独的选项卡中,但我希望能够使用在应用程序中添加的项目更新列表视图,而无需退出然后重新输入到获取列表进行更新。
这是片段Java文件的代码。
正在添加它:
package tabs.ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmedstabbeta;
/**
* Created by WindowsSucks on 10/29/2014.
*/
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
public class AddMedFragment extends Fragment {
private CharSequence mTitle;
final static int RQS_1 = 1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.add_med_layout, container,false);
final TextView medOut = (TextView)rootView.findViewById(R.id.medName);
final TextView doseOut = (TextView)rootView.findViewById(R.id.dosageout);
final TextView timeOut = (TextView)rootView.findViewById(R.id.timeOut);
final TextView dayout = (TextView)rootView.findViewById(R.id.daystxt);
final EditText med_dose = (EditText)rootView.findViewById(R.id.med_dose);
med_dose.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
doseOut.setText(med_dose.getText());
}
@Override
public void afterTextChanged(Editable editable) {
}
});
final Button setTimePickerButton = (Button) rootView.findViewById(R.id.timePickerButton);
setTimePickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog dialog = new TimePickerDialog(getActivity(),
new TimePickerDialog.OnTimeSetListener(){
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
if(selectedHour > 12){
selectedHour-= 12;
}
selectedMinute = timePicker.getCurrentMinute();
if(selectedMinute < 10){
//selectedMinute = String.valueOf(selectedMinute);
timeOut.setText(selectedHour + ":" +"0"+ selectedMinute);
}else{
timeOut.setText(selectedHour + ":" + selectedMinute);
}
}
},hour,minute,false);
dialog.setTitle("Select Time");
dialog.show();
}
});
final TextView medEntry = (TextView) rootView.findViewById(R.id.med_name);
medEntry.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
medOut.setText(medEntry.getText());
}
@Override
public void afterTextChanged(Editable editable) {
}
});
final Button dayPicker = (Button)rootView.findViewById(R.id.dayPicker);
dayPicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final CharSequence[] items = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
// arraylist to keep the selected items
final ArrayList selectedItems=new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Days To Take");
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int indexSelected,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
selectedItems.add(indexSelected);
} else if (selectedItems.contains(indexSelected)) {
// Else, if the item is already in the array, remove it
selectedItems.remove(Integer.valueOf(indexSelected));
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on OK
// You can write the code to save the selected item here
String itemsChecked = selectedItems.toString();
String days = "";
if (itemsChecked.contains("0")) {
days = days + " Sunday";
}
if (itemsChecked.contains("1")) {
days = days + " Monday";
}
if (itemsChecked.contains("2")) {
days = days + " Tuesday";
}
if (itemsChecked.contains("3")) {
days = days + " Wednesday";
}
if (itemsChecked.contains("4")) {
days = days + " Thursday";
}
if (itemsChecked.contains("5")) {
days = days + " Friday";
}
if (itemsChecked.contains("6")) {
days = days + " Saturday";
}
dayout.setText(days);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on Cancel
}
});
AlertDialog dialog = builder.create();//AlertDialog dialog; create like this outside onClick
dialog.show();
}
});
String SDRoot = Environment.getExternalStorageDirectory().getPath();
final File output = new File (SDRoot,"output.txt");
if(!output.exists()){
try {
output.createNewFile();
Context context = getActivity();
CharSequence text = "Output File Created!";
int duration = Toast.LENGTH_LONG;
Toast fileCreated = Toast.makeText(context, text, duration);
fileCreated.show();
} catch (IOException e) {
Context context = getActivity();
CharSequence text = "Output File Not Created!";
int duration = Toast.LENGTH_LONG;
Toast fileNotCreated = Toast.makeText(context, text, duration);
fileNotCreated.show();
e.printStackTrace();
}
}
Button addbutton = (Button)rootView.findViewById(R.id.addMeds);
addbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(),"Medication Added", Toast.LENGTH_SHORT).show();
String outputLine = medOut.getText() + " "+ doseOut.getText() +" "+ dayout.getText() +":" + " "+ ":" + timeOut.getText() + "\n";
try {
FileOutputStream fOut = new FileOutputStream(output, true);
OutputStreamWriter myOutputStreamWriter = new OutputStreamWriter(fOut);
myOutputStreamWriter.append(outputLine);
myOutputStreamWriter.flush();
myOutputStreamWriter.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
ListView list = (ListView) getActivity().findViewById(R.id.viewMedsTxt);
((BaseAdapter)list.getAdapter()).notifyDataSetChanged();
}
});
return rootView;
}
}
正在观看的地方:
package tabs.ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmedstabbeta;
/**
* Created by WindowsSucks on 10/29/2014.
*/
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class ViewMedFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.view_med_layout, container,false);
getActivity().setTitle("View Medications");
// TODO Auto-generated method stub
final ListView lv = (ListView)rootView.findViewById(R.id.viewMedsTxt);
String SDRoot = Environment.getExternalStorageDirectory().getPath();
final File output = new File(SDRoot,"output.txt");
//Get the text file
//Read text from file
StringBuilder text = new StringBuilder();
lv.setItemsCanFocus(true);
final List<String> lines = new ArrayList<>();
Scanner reader = null;
try {
reader = new Scanner(new FileInputStream(output), "UTF-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (reader != null) {
if(!reader.hasNextLine()){
lines.add("You have no medications, add some from the start screen!");
}
}
if (reader != null) {
while(reader.hasNextLine())
lines.add(reader.nextLine());
}
if (reader != null) {
reader.close();
}
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_1,
lines );
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
for (int j = 0; j < parent.getChildCount(); j++)
parent.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);
// change the background color of the selected element
view.setBackgroundColor(Color.LTGRAY);
}
});
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
Button delete = (Button)rootView.findViewById(R.id.deleteMed);
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/** Getting the checked items from the listview */
SparseBooleanArray checkedItemPositions = lv.getCheckedItemPositions();
int itemCount = lv.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
arrayAdapter.remove(lines.get(i));
try {
removeLine(output,i);
} catch (IOException e) {
e.printStackTrace();
}
}
}
checkedItemPositions.clear();
arrayAdapter.notifyDataSetChanged();
Toast.makeText(getActivity(), getString(R.string.medDeleted), Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
public void removeLine(final File file, final int lineIndex) throws IOException{
final List<String> lines = new LinkedList<>();
final Scanner reader = new Scanner(new FileInputStream(file), "UTF-8");
while(reader.hasNextLine())
lines.add(reader.nextLine());
reader.close();
if(lineIndex >= 0 && lineIndex <= lines.size() - 1)
lines.remove(lineIndex);
final BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
for(final String line : lines)
writer.write(line + "\n");
writer.flush();
writer.close();
}
@Override
public void onResume(){
super.onResume();
ListView list = (ListView) getActivity().findViewById(R.id.viewMedsTxt);
((BaseAdapter)list.getAdapter()).notifyDataSetChanged();
}
}
非常感谢!
编辑:
FragmentPageAdapter:
package tabs.ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmedstabbeta;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
public class FragmentPageAdapter extends FragmentPagerAdapter {
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 0:
return new AddMedFragment(medView);
case 1:
return new ViewMedFragment();
default:
break;
}
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}
}
答案 0 :(得分:0)
为什么不使用函数updateMed()创建名为MedUpdateListener的侦听器接口。
public interface MedUpdateListener {
public void updateMed();
}
让ViewMedFrament成为MedUpdateListener并实现updateMed(),以便重新读取您的数据。
public class ViewMedFramgent extends Fragment implements MedUpdateListener{
...
@Override
public void updateMed(){
do some update stuff for your list
}
}
向AddMedFragment添加一个construtor,它接受MEdUpdateListener作为参数:
public class AddMedFragment extends Framgment{
private MedUpdateListener onUpdateListener;
public AddMedFragment(MedUpdateListener onUpdateListener){
this.onUpdateListener = onUpdateListener;
}
}
每当你添加一些内容时:
this.onUpdateLisener.updateMed();
创建碎片时:
public class FragmentPageAdapter extends FragmentPagerAdapter {
private Fragment[] frags = new Fragment[2];
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
frags[0] = new ViewMedFragment();
frags[1] = new AddMedFragment(frags[0]);
}
@Override
public Fragment getItem(int pos) {
return frags[pos];
}
@Override
public int getCount() {
return frags.length();
}
}
在你的addButton
中调用onUpdateListener.updateMed()