我最近创建了一个带有底部导航模板的新应用程序。我把代码放在activity.xml和mainactivity.java文件中。但我意识到,我想把它们放在fragment\u home.xml文件中,把java放在homepragment.java文件中。所有的xml仅仅是一个按钮和一个文本视图,所以我复制并粘贴在fragment\u home.xml文件中,但是将java从mainactivity.java复制到homefragment.java并不是那么容易。这是第一次使用底部导航模板,我不知道该把代码放在哪里,maintivity.java中的代码,在homepragment.java文件中显示红线。因为我没有使用片段及其专门语法的经验,所以我在这里寻求帮助。我想找一个更有经验的人来帮助我将代码从mainacivity迁移到homepragment,而不会出错。这是密码。
活动\u 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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="?attr/actionBarSize"
>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/bottom_nav_menu" />
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="408dp"
android:layout_height="742dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="@id/nav_view"
app:layout_constraintHorizontal_bias="0.333"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:navGraph="@navigation/mobile_navigation" />
<TextView
android:id="@+id/text_view_result"
android:layout_width="194dp"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#0A0A0A"
app:layout_constraintBottom_toTopOf="@+id/nav_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.287" />
<Button
android:id="@+id/button_parse"
android:layout_width="194dp"
android:layout_height="71dp"
android:text="Parse"
app:layout_constraintBottom_toTopOf="@+id/nav_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/nav_host_fragment"
app:layout_constraintVertical_bias="0.419" />
</androidx.constraintlayout.widget.ConstraintLayout>
mainactivity.java:
package com.example.spoonacular;
import android.app.VoiceInteractor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Array;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private TextView mTextViewResult;
private RequestQueue mQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
mTextViewResult = findViewById(R.id.text_view_result);
Button buttonParse = findViewById(R.id.button_parse);
mQueue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse() {
String url = "https://api.spoonacular.com/recipes/random?number=1&tags=vegetarian,dessert&apiKey=86912d6bb1474577a76513e236a8a58e";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("recipes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject recipes = jsonArray.getJSONObject(i);
Boolean vegetarian = recipes.getBoolean("vegetarian");
Boolean vegan = recipes.getBoolean("vegan");
Boolean glutenFree = recipes.getBoolean("glutenFree");
Boolean dairyFree = recipes.getBoolean("dairyFree");
Boolean veryHealthy = recipes.getBoolean("veryHealthy");
Boolean cheap = recipes.getBoolean("cheap");
Boolean veryPopular = recipes.getBoolean("veryPopular");
Boolean sustainable = recipes.getBoolean("sustainable");
Boolean lowFodmap = recipes.getBoolean("lowFodmap");
int weightWatcherSmartPoints = recipes.getInt("weightWatcherSmartPoints");
int spoonacularScore = recipes.getInt("spoonacularScore");
int healthScore = recipes.getInt("healthScore");
int pricePerServing = recipes.getInt("pricePerServing");
int likes = recipes.getInt("aggregateLikes");
String gaps = recipes.getString("gaps");
String source = recipes.getString("sourceName");
mTextViewResult.setText("Vegetarian: " + vegetarian + "\n\n"+ "Vegan: " + vegan + "\n\n" + "Gluten Free: " + glutenFree + "\n\n" + "Dairy Free: " + dairyFree + "\n\n" + "Very Healthy: " + veryHealthy + "\n\n"+ "Cheap: " + cheap + "\n\n" + "Very Popular: " + veryPopular + "\n\n" + "Sustainable: " + sustainable + "\n\n" + "Low Fod Map: " + lowFodmap + "\n\n" + "Weight Watcher Points: " + String.valueOf(weightWatcherSmartPoints) + "\n\n" + "Spoonacular Score: " + String.valueOf(spoonacularScore) + "\n\n" + "Health Score: " + String.valueOf(healthScore) + "\n\n" + "Price Per Serving: " + String.valueOf(pricePerServing) + "\n\n" + "Likes: " + String.valueOf(likes) + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
移动到fragment_home.xml和homefragment java文件注意,这里没有我编写的代码,这些都是从底部导航模板预编码的默认值
片段\u home.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=".ui.home.HomeFragment">
<TextView
android:id="@+id/text_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
homefragment.java文件,
package com.example.spoonacular.ui.home;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import com.example.spoonacular.R;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
new ViewModelProvider(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
final TextView textView = root.findViewById(R.id.text_home);
homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
而且,由于显示homeviewmodel文件可能也很有用(不过,如果有人能向我解释homeviewmodel.java和homefragment.java之间的区别,我将不胜感激)
homeviewmodel.java文件
package com.example.spoonacular.ui.home;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class HomeViewModel extends ViewModel {
private MutableLiveData<String> mText;
public HomeViewModel() {
mText = new MutableLiveData<>();
mText.setValue("This is home fragment");
}
public LiveData<String> getText() {
return mText;
}
}
我知道这是一个很长的问题,可能不值得回答,但我一直未能找到解决办法,这是我最后的希望。我已经准备好回答任何问题(并且投票并接受有效的解决方案)谢谢您的帮助!
编辑
主活动.java
package com.example.spoonacular;
import android.os.Bundle;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
}
}
主页片段.java
package com.example.spoonacular.ui.home;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.spoonacular.R;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class HomeFragment extends Fragment {
private TextView mTextViewResult;
private Button buttonParse;
private HomeViewModel homeViewModel;
private RequestQueue mQueue;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
new ViewModelProvider(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
mTextViewResult = root.findViewById(R.id.text_view_result);
buttonParse = root.findViewById(R.id.button_parse);
mQueue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
jsonParse();
}
});
homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
mTextViewResult.setText(s);
}
});
return root;
}
private void jsonParse() {
String url = "https://api.spoonacular.com/recipes/random?number=1&tags=vegetarian,dessert&apiKey=86912d6bb1474577a76513e236a8a58e";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("recipes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject recipes = jsonArray.getJSONObject(i);
Boolean vegetarian = recipes.getBoolean("vegetarian");
Boolean vegan = recipes.getBoolean("vegan");
Boolean glutenFree = recipes.getBoolean("glutenFree");
Boolean dairyFree = recipes.getBoolean("dairyFree");
Boolean veryHealthy = recipes.getBoolean("veryHealthy");
Boolean cheap = recipes.getBoolean("cheap");
Boolean veryPopular = recipes.getBoolean("veryPopular");
Boolean sustainable = recipes.getBoolean("sustainable");
Boolean lowFodmap = recipes.getBoolean("lowFodmap");
int weightWatcherSmartPoints = recipes.getInt("weightWatcherSmartPoints");
int spoonacularScore = recipes.getInt("spoonacularScore");
int healthScore = recipes.getInt("healthScore");
int pricePerServing = recipes.getInt("pricePerServing");
int likes = recipes.getInt("aggregateLikes");
String gaps = recipes.getString("gaps");
String source = recipes.getString("sourceName");
mTextViewResult.setText("Vegetarian: " + vegetarian + "\n\n" + "Vegan: " + vegan + "\n\n" + "Gluten Free: " + glutenFree + "\n\n" + "Dairy Free: " + dairyFree + "\n\n" + "Very Healthy: " + veryHealthy + "\n\n" + "Cheap: " + cheap + "\n\n" + "Very Popular: " + veryPopular + "\n\n" + "Sustainable: " + sustainable + "\n\n" + "Low Fod Map: " + lowFodmap + "\n\n" + "Weight Watcher Points: " + String.valueOf(weightWatcherSmartPoints) + "\n\n" + "Spoonacular Score: " + String.valueOf(spoonacularScore) + "\n\n" + "Health Score: " + String.valueOf(healthScore) + "\n\n" + "Price Per Serving: " + String.valueOf(pricePerServing) + "\n\n" + "Likes: " + String.valueOf(likes) + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
片段\u home.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=".ui.home.HomeFragment">
<TextView
android:id="@+id/text_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/text_view_result"
android:layout_width="194dp"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#0A0A0A"
app:layout_constraintBottom_toTopOf="@+id/nav_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.287" />
<Button
android:id="@+id/button_parse"
android:layout_width="194dp"
android:layout_height="71dp"
android:text="Parse"
app:layout_constraintBottom_toTopOf="@+id/nav_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/nav_host_fragment"
app:layout_constraintVertical_bias="0.419" />
</androidx.constraintlayout.widget.ConstraintLayout>
活动\u 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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="?attr/actionBarSize"
>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/bottom_nav_menu" />
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="408dp"
android:layout_height="742dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="@id/nav_view"
app:layout_constraintHorizontal_bias="0.333"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
homefragment.java中仍有错误
第44行
mQueue = Volley.newRequestQueue(this);
1条答案
按热度按时间7fyelxc51#
我不知道,我只是从
MainActivity
至HomeFragment
.主要活动
家庭碎片
主要活动
你回家了吗