#android #android-fragments #android-activity #android-listfragment
#Android #android-фрагменты #android-activity #android-listfragment
Вопрос:
Здравствуйте, я пытаюсь создать приложение, которое перейдет от основного действия (экран входа в систему) к фрагменту с listview (отображает имя из логина), а затем вернет один из параметров listview к основному действию (повторно введите имя, адрес электронной почты и адрес). Я пытался заставить это работать, но я не могу сказать, что не так, я бы предположил, поскольку я новичок в программировании.
Это XML и классы:
MainActivity.java
package com.example.project;
import android.app.Fragment;
import android.os.Bundle;
import android.provider.Telephony;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public Button login;
public EditText name;
public EditText email;
public EditText address;
String Name;
String Email;
String Address;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Button login = (Button) findViewById(R.id.button);
EditText name = (EditText) findViewById(R.id.name);
EditText email = (EditText) findViewById(R.id.email);
EditText address = (EditText) findViewById(R.id.address);
String Name = name.getText().toString();
String Email = email.getText().toString();
String Address = address.getText().toString();
Fragment fragment = new ListViewFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.mainFrag, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
private void showFragment(){
Bundle info = new Bundle();
info.putString("name", Name);
info.putString("email", Email);
info.putString("address", Address);
Fragment fragment = new Fragment();
fragment.setArguments(info);
android.app.FragmentTransaction transaction = getFragmentManager().beginTransaction();
// transaction.setCustomAnimations(R.animator.fade_in, R.animator.fade_out);
transaction.addToBackStack(null);
transaction.replace(R.id.account, fragment);
transaction.commit();
}
}
activity_main.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:id="@ id/mainFrag"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@ id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Smart-Home Sensors System"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<fragment
android:id="@ id/fragment"
android:name="com.example.project.ListViewFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@ id/textView" />
<Button
android:id="@ id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.931" />
<EditText
android:id="@ id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@ id/textView" />
<EditText
android:id="@ id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Email"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@ id/name" />
<EditText
android:id="@ id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Address"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@ id/email" />
</androidx.constraintlayout.widget.ConstraintLayout>
ListViewFragment.java
package com.example.project;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import java.lang.reflect.Array;
import java.util.ArrayList;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
public class ListViewFragment extends Fragment {
String myValue = this.getArguments().getString("message");
public static ListViewFragment newInstance(String name, String email, String password) {
ListViewFragment f = new ListViewFragment();
/*
Bundle args = new Bundle();
args.putString("Name", name);
args.putString("Email", email);
args.putString("Password", password);
f.setArguments(args);*/
return f;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.mainmenu, container, false);
final ListView list = getView().findViewById(R.id.list);
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("View sensor 1");
arrayList.add("View sensor 2");
arrayList.add("View login details");
arrayList.add("Logout");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getView().getContext(), android.R.layout.simple_list_item_1, arrayList);
list.setAdapter(arrayAdapter);
TextView textView = new TextView(getView().getContext());
textView.setText("Please select an option:");
list.addHeaderView(textView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
private void showFragment() {
Fragment fragment = new Fragment();
FragmentTransaction transaction =
getFragmentManager().beginTransaction();
transaction.addToBackStack(null);
// transaction.setCustomAnimations(R.animator.fade_in, R.animator.fade_out);
transaction.replace(R.id.account, fragment, "fragment");
transaction.commit();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String clickedItem = (String) list.getItemAtPosition(position);
Toast.makeText(getView().getContext(), clickedItem, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getView().getContext(), LoginFragment.class);
intent.putExtra(EXTRA_MESSAGE, clickedItem);
startActivity(intent);
}
});
return v;
}
private void showSigninFragment(Fragment showinfo){
Fragment fragment = showinfo;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//transaction.setCustomAnimations(R.animator.fade_in, R.animator.fade_out);
transaction.addToBackStack(null);
transaction.replace(R.id.account, fragment);
transaction.commit();
}
}
mainmenu.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">
<TextView
android:id="@ id/nameDisp"
android:layout_width="95dp"
android:layout_height="34dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_weight="1"
android:text="TextView"
app:layout_constraintBottom_toTopOf="@ id/list"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.552" />
<TextView
android:id="@ id/emailDisp"
android:layout_width="90dp"
android:layout_height="38dp"
android:layout_weight="1"
android:text="TextView"
app:layout_constraintBottom_toTopOf="@ id/list"
app:layout_constraintEnd_toStartOf="@ id/nameDisp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@ id/addressDisp"
android:layout_width="95dp"
android:layout_height="34dp"
android:layout_marginEnd="48dp"
android:layout_marginRight="48dp"
android:layout_weight="1"
android:text="TextView"
app:layout_constraintBottom_toTopOf="@ id/list"
app:layout_constraintEnd_toStartOf="@ id/emailDisp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.552" />
<ListView
android:id="@ id/list"
android:layout_width="381dp"
android:layout_height="496dp"
android:layout_marginTop="72dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@ id/selectOption"
android:layout_width="189dp"
android:layout_height="98dp"
android:layout_weight="1"
android:hint="@string/testStringForToast"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@ id/list" />
</androidx.constraintlayout.widget.ConstraintLayout>
Комментарии:
1. Обновлены ваши теги.
android-studio
тег следует использовать только для вопросов / ошибок о продукте Android Studio. Ваш вопрос не о Android Studio, поэтому я удалил тег и добавилandroid
вместо него общий тег.
Ответ №1:
Вместо
import android.app.Fragment;
вы должны импортировать
import androidx.fragment.app.Fragment;
и в showFragment() в вашем основном Activity.java
// create new ListViewFragment ("ListViewFragment.java" ...)
ListViewFragment lvFragment = new ListViewFragment();
// create new FragmentManager
FragmentManager fm = getSupportFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction transaction = fm.beginTransaction();
// your animation...
transaction.setCustomAnimations(R.animator.fade_in, R.animator.fade_out);
// replace your activity_main layout with your Fragment layout
transaction.add(R.id.mainFrag, lvFragment);
transaction.addToBackStack("");
transaction.commit(); // save changes
вы можете удалить <fragment...
из activity_main.xml