У меня есть проблемы, соединив один fragment
с какой-то существующей деятельностью в моем app, что я пробую сделать, состоит в том, чтобы перемещать содержание одного EditText
деятельности в fragment
и наоборот.
У меня есть следующие переменные:
private TextView texto;
private ListView lista;
private EditText editText;
private Button boton;
И в строителя я это помещаю:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_fragment, container, false);
texto= (TextView) v.findViewById(R.id.changeView);
lista= (ListView) v.findViewById(R.id.listView);
editText= (EditText) v.findViewById(R.id.fragmentEditText);
boton= (Button) v.findViewById(R.id.fragmentButton);
boton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.botonComunicacion(editText.getText().toString());
}
});
lista.setOnItemClickListener(this);
return v;
}
но отсюда брать данные, я затрудняюсь: Вы могли бы давать мне какую-то идею?
Чтобы посылать данные одному Fragment
с одной Activity
ты можешь реализовывать это посредством одного Bundle
.
Bundle bundle = new Bundle();
bundle.putString("valorEditText", "From Activity");
MyFragment myFragment = new MyFragment ();
//Agrega bundle como argumento al fragment.
myFragment.setArguments(bundle);
В método onCreateView()
из Fragment ты получаешь стоимость:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Aquí recibimos el valor.
String valorEditTextdeFragment = getArguments().getString("valorEditText");
return inflater.inflate(R.layout.fragment, container, false);
}
Сначала чтобы иметь comunicaci¦n с Активности - fragment tendr¦-эксперт, который должен создавать fragment и производить funci¦n на писания текста fragment.
public void changeText(String string){
texto.setText(string);
}
потом в активности, где ты захотел послать эту информацию fragment осуществлять Вашу глобальную переменную
private fragment frag;
инициализировать
frag= (fragment) getFragmentManager().findFragmentById(R.id.fragment);
и иметь funci¦n посылания info или Эдит Текст в fragment.
public void sendInfo(View v){
frag.changeText(editText.getText().toString());
}
Después, производить interacci¦n fragment-активность. Ты нуждаешься в Интерфейсе fragment OnFragmentInteractionListener
в том, чтобы изменить ее и добавить функцию comunicaci¦n, 'void botonComunicacion (String string);
после того, как это имеешь, ты нуждаешься в функции внутри активности
public void botonComunicacion(String string) {
texto.setText(string);
}
В тебе fragment
hata внизу у тебя есть одна interface
, где ты можешь помещать все методы, которые ты хочешь например:
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
ты можешь снимать функцию, которая у него есть, и добавлять другую, в твоем случае он остался бы так:
public interface OnFragmentInteractionListener {
void BotonComunicacion(String string);
}
Так как в твоей кнопке ты посылаешь звонить, - функция, только убедись, что, где звонил ты fragment
имей осуществленный функцию OnFragmentInteractionListener
:
public class actividad extends AppCompatActivity implements fragmment.OnFragmentInteractionListener {
}
Однажды осуществленный он попросит у тебя осуществлять твою функцию BotonComunicacion
где эта функция - та, которая будет получать информацию, когда ты посылаешь называть ее в тебе fragment
все, что они это нажимают.
В fragment ты можешь издавать это с дисплеем данных, в fragment ты можешь помещать
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), Datos.class);
intent.putExtra("nombre", arrayList.get(position).getNombre());
startActivity(intent);
В класс данные
private TextView nombre;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visualizacion__datos);
nombre = (TextView) findViewById(R.id.nombreDato);
Intent intent = getIntent();
}
Файл Properties
Properties properties;
File file = new File(getFilesDir(),FILENAME);
properties = new Properties();
try{
if(file.exists()){
FileInputStream fis=openFileInput(FILENAME);
properties.loadFromXML(fis);
fis.close();
Toast.makeText(this,"PROPERTIES LOADED FROM FILE",Toast.LENGTH_SHORT).show();
}
else{
saveStorage();
Toast.makeText(this,"PROPERTIES FILE CREATED ON DEVICE",Toast.LENGTH_SHORT).show();
}
}
catch(Exception e){
e.printStackTrace();
}
public void saveStorage() throws Exception {
saveProperties();
FileOutputStream fos=openFileOutput(FILENAME, Context.MODE_PRIVATE);
properties.storeToXML(fos,null);
fos.close();
}
public void saveProperties(){
properties.setProperty("name", inputText.getText().toString());
}
public void saveStorageButton(View v){
try{
saveStorage();
Toast.makeText(this,"SAVE IN STORAGE", Toast.LENGTH_SHORT).show();
}
catch(Exception e){
e.printStackTrace();
}
}
Лучшая форма - в trávez Listener
public interface TextListener {
void sendText(String text);
}
и который осуществил твой activity и твой fragment
с activity:
((TextListener) fragment).sendText("texto a enviar al fragment");
с fragment
((TextListener) getActivity()).sendText("texto a enviar al activity");