liuqirui_part
刘骐瑞 2 months ago
parent be3945fb1e
commit 5b3b5c1923

@ -50,6 +50,8 @@ dependencies {
// Kotlin
implementation "org.jetbrains.kotlin:kotlin-stdlib:1.8.20"
implementation 'com.google.android.flexbox:flexbox:3.0.0'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
//
implementation project(':mainnavigatetabbar')

@ -1,113 +1,474 @@
package com.startsmake.llrisetabbardemo.fragment;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.startsmake.llrisetabbardemo.R;
import com.startsmake.llrisetabbardemo.activity.MainActivity;
import com.startsmake.llrisetabbardemo.adapter.ProductAdapter;
import com.startsmake.llrisetabbardemo.model.Item;
import com.startsmake.llrisetabbardemo.adapter.SearchAdapter;
import com.startsmake.llrisetabbardemo.activity.SearchActivity;
import com.startsmake.llrisetabbardemo.activity.SearchResultsActivity;
import com.startsmake.llrisetabbardemo.model.Product;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* User:Shine
* Date:2015-10-20
* Description:
*/
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private ProductAdapter adapter;
private List<Item> itemList = new ArrayList<>();
private EditText searchEditText;
private ImageButton cameraButton;
private TextView homeSearchButton;
// 首页商品展示相关
private RecyclerView homeProductsRecyclerView;
private TextView homeNoProductsText;
private LinearLayout defaultContent;
// 导航栏按钮
private RadioButton tabFollow;
private TextView tabRecommend, tabNew, tabStudy, tabLiving;
// 随机标签相关
private List<String> randomKeywords;
private Handler handler;
private Runnable keywordRunnable;
private static final long KEYWORD_CHANGE_INTERVAL = 3000;
private static final int CAMERA_REQUEST_CODE = 101;
private static final int CAMERA_PERMISSION_REQUEST_CODE = 102;
private String currentPhotoPath;
private List<Product> productList;
private SearchAdapter searchAdapter;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
initSearchData();
initRandomKeywords();
setupNavigationButtons();
startKeywordRotation();
// 默认显示推荐内容
showRandomRecommendations();
tabRecommend.setTextColor(0xffff6b35);
}
private void initViews(View view) {
searchEditText = view.findViewById(R.id.search_edit_text);
cameraButton = view.findViewById(R.id.camera_button);
homeSearchButton = view.findViewById(R.id.home_search_button);
// 首页商品展示相关视图
homeProductsRecyclerView = view.findViewById(R.id.home_products_recycler_view);
homeNoProductsText = view.findViewById(R.id.home_no_products_text);
defaultContent = view.findViewById(R.id.default_content);
// 初始化导航栏按钮
tabFollow = view.findViewById(R.id.tab_follow);
tabRecommend = view.findViewById(R.id.tab_recommend);
tabNew = view.findViewById(R.id.tab_new);
tabStudy = view.findViewById(R.id.tab_study);
tabLiving = view.findViewById(R.id.tab_living);
// 设置首页商品RecyclerView
setupHomeProductsRecyclerView();
searchEditText.setOnClickListener(v -> {
Intent intent = new Intent(getActivity(), SearchActivity.class);
startActivity(intent);
});
homeSearchButton.setOnClickListener(v -> {
performHomeSearch();
});
cameraButton.setOnClickListener(v -> {
if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
}
});
}
// 设置首页商品RecyclerView
private void setupHomeProductsRecyclerView() {
homeProductsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
searchAdapter = new SearchAdapter(new ArrayList<>());
homeProductsRecyclerView.setAdapter(searchAdapter);
}
// 设置导航栏按钮点击事件
private void setupNavigationButtons() {
// 关注按钮
tabFollow.setOnClickListener(v -> {
resetTabColors();
tabFollow.setTextColor(0xffff6b35);
showFollowedProducts();
});
// 推荐按钮
tabRecommend.setOnClickListener(v -> {
resetTabColors();
tabRecommend.setTextColor(0xffff6b35);
showRandomRecommendations();
});
// 初始化 RecyclerView
recyclerView = view.findViewById(R.id.recyclerViewProducts);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
// 新发布按钮
tabNew.setOnClickListener(v -> {
resetTabColors();
tabNew.setTextColor(0xffff6b35);
showNewProducts();
});
// 初始化商品列表
initProductList();
// 学习资料按钮
tabStudy.setOnClickListener(v -> {
resetTabColors();
tabStudy.setTextColor(0xffff6b35);
showStudyProducts();
});
// 设置适配器
adapter = new ProductAdapter(getContext(), itemList, item -> {
// 点击商品跳转到详情页面
showItemDetail(item);
// 生活用品按钮
tabLiving.setOnClickListener(v -> {
resetTabColors();
tabLiving.setTextColor(0xffff6b35);
showLifeProducts();
});
}
// 重置所有标签颜色为未选中状态
private void resetTabColors() {
tabFollow.setTextColor(0xff666666);
tabRecommend.setTextColor(0xff666666);
tabNew.setTextColor(0xff666666);
tabStudy.setTextColor(0xff666666);
tabLiving.setTextColor(0xff666666);
}
// 显示随机推荐商品
private void showRandomRecommendations() {
if (productList == null || productList.isEmpty()) {
showNoProducts();
return;
}
List<Product> shuffledList = new ArrayList<>(productList);
Collections.shuffle(shuffledList);
int count = Math.min(6, shuffledList.size());
List<Product> randomProducts = shuffledList.subList(0, count);
showHomeProducts(randomProducts);
Toast.makeText(requireContext(), "为您推荐", Toast.LENGTH_SHORT).show();
}
// 显示新发布商品
private void showNewProducts() {
List<Product> newProducts = new ArrayList<>();
for (Product product : productList) {
if (Integer.parseInt(product.getId()) > 3) {
newProducts.add(product);
}
}
if (newProducts.isEmpty()) {
showNoProducts();
} else {
showHomeProducts(newProducts);
Toast.makeText(requireContext(), "新发布商品", Toast.LENGTH_SHORT).show();
}
}
// 显示学习资料类商品
private void showStudyProducts() {
List<Product> studyProducts = new ArrayList<>();
for (Product product : productList) {
if ("学习资料".equals(product.getCategory())) {
studyProducts.add(product);
}
}
if (studyProducts.isEmpty()) {
showNoProducts();
} else {
showHomeProducts(studyProducts);
Toast.makeText(requireContext(), "学习资料", Toast.LENGTH_SHORT).show();
}
}
// 显示生活用品类商品
private void showLifeProducts() {
List<Product> lifeProducts = new ArrayList<>();
for (Product product : productList) {
if ("生活用品".equals(product.getCategory())) {
lifeProducts.add(product);
}
}
if (lifeProducts.isEmpty()) {
showNoProducts();
} else {
showHomeProducts(lifeProducts);
Toast.makeText(requireContext(), "生活用品", Toast.LENGTH_SHORT).show();
}
}
// 显示关注用户的商品
private void showFollowedProducts() {
List<Product> followedProducts = new ArrayList<>();
if (productList.size() >= 2) {
followedProducts.add(productList.get(0));
followedProducts.add(productList.get(1));
}
if (followedProducts.isEmpty()) {
showNoProducts();
Toast.makeText(requireContext(), "您还没有关注任何用户", Toast.LENGTH_SHORT).show();
} else {
showHomeProducts(followedProducts);
Toast.makeText(requireContext(), "关注用户的商品", Toast.LENGTH_SHORT).show();
}
}
// 在首页显示商品
private void showHomeProducts(List<Product> products) {
searchAdapter.updateData(products);
homeProductsRecyclerView.setVisibility(View.VISIBLE);
homeNoProductsText.setVisibility(View.GONE);
defaultContent.setVisibility(View.GONE);
}
// 显示暂无商品
private void showNoProducts() {
homeProductsRecyclerView.setVisibility(View.GONE);
homeNoProductsText.setVisibility(View.VISIBLE);
defaultContent.setVisibility(View.GONE);
}
// 显示默认内容
private void showDefaultContent() {
homeProductsRecyclerView.setVisibility(View.GONE);
homeNoProductsText.setVisibility(View.GONE);
defaultContent.setVisibility(View.VISIBLE);
}
// 初始化随机标签列表
private void initRandomKeywords() {
randomKeywords = Arrays.asList(
"Java编程教材", "Python入门书籍", "高等数学课本", "英语四级真题", "考研政治资料", "计算机专业课", "电路分析教程", "机械制图教材", "经济学原理", "心理学导论", "设计素描本", "专业课程笔记","二手笔记本电脑", "机械键盘", "无线鼠标", "蓝牙耳机", "平板电脑", "智能手机", "充电宝", "U盘硬盘", "显示器", "路由器", "相机镜头", "游戏手柄", "收纳箱", "穿衣镜",
"瑜伽垫", "体重秤", "电风扇", "暖手宝", "床上桌", "衣柜", "鞋架", "晾衣架","羽毛球拍", "篮球足球", "滑板轮滑", "吉他乐器",
"画笔画具", "围棋象棋", "游泳装备", "健身器材", "登山背包", "帐篷睡袋", "摄影三脚架", "书法字帖"
);
handler = new Handler();
}
// 开始标签轮换
private void startKeywordRotation() {
keywordRunnable = new Runnable() {
@Override
public void run() {
if (randomKeywords != null && !randomKeywords.isEmpty()) {
Collections.shuffle(randomKeywords);
String randomKeyword = randomKeywords.get(0);
searchEditText.setHint(randomKeyword);
}
handler.postDelayed(this, KEYWORD_CHANGE_INTERVAL);
}
};
handler.post(keywordRunnable);
}
// 首页搜索功能
private void performHomeSearch() {
String currentHint = searchEditText.getHint().toString();
String defaultHint = getResources().getString(R.string.search_hint);
if (!currentHint.equals(defaultHint) && randomKeywords.contains(currentHint)) {
Intent intent = new Intent(getActivity(), SearchResultsActivity.class);
intent.putExtra("search_query", currentHint);
startActivity(intent);
} else {
Intent intent = new Intent(getActivity(), SearchActivity.class);
startActivity(intent);
}
}
private void initSearchData() {
productList = new ArrayList<>();
productList.add(new Product("1", "Java编程思想", "计算机专业教材", "学习资料", 45.0, ""));
productList.add(new Product("2", "高等数学教材", "大学数学课本", "学习资料", 30.0, ""));
productList.add(new Product("3", "笔记本电脑", "二手联想笔记本", "数码产品", 1200.0, ""));
productList.add(new Product("4", "台灯", "护眼学习台灯", "生活用品", 25.0, ""));
productList.add(new Product("5", "Python入门", "编程学习书籍", "学习资料", 35.0, ""));
productList.add(new Product("6", "数据结构与算法", "计算机专业书籍", "学习资料", 40.0, ""));
productList.add(new Product("7", "水杯", "保温水杯", "生活用品", 20.0, ""));
productList.add(new Product("8", "插排", "多功能插排", "生活用品", 35.0, ""));
}
// 原有的搜索方法保持不变
private void performSearch() {
String query = searchEditText.getText().toString().trim();
if (!query.isEmpty()) {
hideKeyboard();
List<Product> searchResults = searchProducts(query);
if (searchResults.isEmpty()) {
// 这里使用原有的搜索结果显示逻辑
showNoResults();
} else {
// 这里使用原有的搜索结果显示逻辑
showSearchResults(searchResults);
}
} else {
showDefaultContent();
}
}
// 原有的搜索结果显示方法
private void showSearchResults(List<Product> results) {
// 这里使用原有的搜索结果RecyclerView
// searchAdapter.updateData(results);
// searchResultsRecyclerView.setVisibility(View.VISIBLE);
// noResultsText.setVisibility(View.GONE);
// defaultContent.setVisibility(View.GONE);
}
private void showNoResults() {
// 原有的无结果显示逻辑
// searchResultsRecyclerView.setVisibility(View.GONE);
// noResultsText.setVisibility(View.VISIBLE);
// defaultContent.setVisibility(View.GONE);
}
private List<Product> searchProducts(String keyword) {
List<Product> results = new ArrayList<>();
for (Product product : productList) {
if (product.getName().toLowerCase().contains(keyword.toLowerCase()) ||
product.getDescription().toLowerCase().contains(keyword.toLowerCase()) ||
product.getCategory().toLowerCase().contains(keyword.toLowerCase())) {
results.add(product);
}
}
return results;
}
// 隐藏软键盘的方法
private void hideKeyboard() {
InputMethodManager imm = (InputMethodManager) requireContext().getSystemService(Context.INPUT_METHOD_SERVICE);
View currentFocus = requireActivity().getCurrentFocus();
if (currentFocus != null) {
imm.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
Toast.makeText(requireContext(), "需要相机权限才能拍照搜索", Toast.LENGTH_SHORT).show();
}
}
}
recyclerView.setAdapter(adapter);
return view;
}
private void initProductList() {
// 添加一些示例商品
itemList.clear();
// 示例商品1
Item item1 = new Item();
item1.setTitle("全新iPhone 13 Pro");
item1.setDescription("全新未拆封256GB远峰蓝色国行正品");
item1.setPrice(6999.00);
item1.setCategory("数码产品");
item1.setLocation("北京");
item1.setContact("138****1234");
item1.setPublishTime(System.currentTimeMillis() - 2 * 60 * 60 * 1000); // 2小时前
itemList.add(item1);
// 示例商品2
Item item2 = new Item();
item2.setTitle("二手笔记本电脑");
item2.setDescription("联想小新i5处理器8GB内存256GB固态硬盘");
item2.setPrice(2500.00);
item2.setCategory("数码产品");
item2.setLocation("上海");
item2.setContact("微信abc123");
item2.setPublishTime(System.currentTimeMillis() - 5 * 60 * 60 * 1000); // 5小时前
itemList.add(item2);
// 示例商品3
Item item3 = new Item();
item3.setTitle("品牌运动鞋");
item3.setDescription("耐克运动鞋42码只穿过几次几乎全新");
item3.setPrice(299.00);
item3.setCategory("服装鞋帽");
item3.setLocation("广州");
item3.setContact("159****5678");
item3.setPublishTime(System.currentTimeMillis() - 24 * 60 * 60 * 1000); // 1天前
itemList.add(item3);
}
private void showItemDetail(Item item) {
// 创建商品详情Fragment
ItemDetailFragment detailFragment = ItemDetailFragment.newInstance(item);
// 使用FragmentTransaction显示详情页面
FragmentTransaction transaction = getParentFragmentManager().beginTransaction();
transaction.replace(R.id.container, detailFragment);
transaction.addToBackStack("item_detail");
transaction.commit();
}
// 添加新商品到列表(在发布成功后调用)
public void addNewItem(Item item) {
if (itemList != null && adapter != null) {
// 将新发布的商品添加到列表顶部
itemList.add(0, item);
adapter.notifyItemInserted(0);
// 滚动到顶部
recyclerView.smoothScrollToPosition(0);
private void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(requireActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Toast.makeText(requireContext(), "创建文件失败", Toast.LENGTH_SHORT).show();
}
if (photoFile != null) {
currentPhotoPath = photoFile.getAbsolutePath();
Uri photoURI = FileProvider.getUriForFile(requireContext(),
requireContext().getPackageName() + ".fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
} else {
Toast.makeText(requireContext(), "未找到相机应用", Toast.LENGTH_SHORT).show();
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(
imageFileName,
".jpg",
storageDir
);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if (currentPhotoPath != null) {
Toast.makeText(requireContext(), "拍照成功,开始搜索...", Toast.LENGTH_SHORT).show();
searchEditText.setText("图片搜索中...");
performSearch();
}
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (handler != null && keywordRunnable != null) {
handler.removeCallbacks(keywordRunnable);
}
}
}

@ -1,3 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
@ -17,7 +18,7 @@
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginTop="2.5dp"
android:alpha="0.8"
android:background="@drawable/rounded_background1"
android:gravity="center_vertical"
@ -40,11 +41,10 @@
android:layout_weight="1"
android:alpha="1"
android:background="@null"
android:focusable="true"
android:focusableInTouchMode="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:hint="搜索教材、数码、生活用品..."
android:imeOptions="actionSearch"
android:inputType="text"
android:inputType="none"
android:maxLines="1"
android:paddingStart="8dp"
android:paddingEnd="8dp"
@ -53,6 +53,7 @@
android:textColorHint="#999999"
android:textSize="14sp" />
<!-- 摄像头按钮 -->
<ImageButton
android:id="@+id/camera_button"
android:layout_width="23dp"
@ -64,6 +65,21 @@
android:src="@android:drawable/ic_menu_camera"
android:contentDescription="拍照搜索" />
<!-- 搜索按钮 -->
<TextView
android:id="@+id/home_search_button"
android:layout_width="50dp"
android:layout_height="27dp"
android:layout_marginStart="2dp"
android:layout_marginTop="0dp"
android:gravity="center"
android:text="搜索"
android:textColor="#333333"
android:textSize="14sp"
android:textStyle="bold"
android:clickable="true"
android:focusable="true" />
</LinearLayout>
</LinearLayout>
@ -166,12 +182,44 @@
</LinearLayout>
</HorizontalScrollView>
<!-- 商品列表区域 - 新增部分 -->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerViewProducts"
<!-- 商品展示区域 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<!-- 商品列表 -->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/home_products_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
<!-- 暂无商品提示 -->
<TextView
android:id="@+id/home_no_products_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="暂无商品"
android:textColor="#666666"
android:textSize="16sp"
android:visibility="gone" />
</LinearLayout>
<!-- 首页默认内容区域 -->
<LinearLayout
android:id="@+id/default_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="120dp"
android:padding="8dp" />
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">
<!-- 这里可以放默认的首页内容 -->
</LinearLayout>
</FrameLayout>
Loading…
Cancel
Save