有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何根据单击的位置在GridView中选择TextView?

我使用一个片段,其中我使用GridView生成一些类别。当用户选择一个类别时,我将用一个新的片段替换前面的片段,该片段用于获取类别的详细信息。但是当我回到显示类别的前一个片段时,我想选择用户先前单击的类别。我曾尝试使用选择器,但它对我不起作用。这是我的密码

这是我的布局xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    安卓:orientation="vertical"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:paddingTop="20dp"
    >
    <GridView
        安卓:id="@+id/hindernisTypGridView"
        安卓:layout_width="match_parent"
        安卓:layout_height="match_parent"
        安卓:numColumns="auto_fit"
        安卓:columnWidth="190dp"
        安卓:verticalSpacing="20dp"
        安卓:layout_below="@+id/topBar"
        安卓:horizontalSpacing="5dp"
        安卓:paddingLeft="32dp"
        安卓:paddingRight="32dp"
        />
</LinearLayout>

这是我为gridview定制的xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:tools=" http://schemas.安卓.com/tools"
    安卓:orientation="vertical"
    安卓:layout_width="190dp"
    安卓:layout_height="180dp"
    安卓:padding="2dp"
    tools:ignore="MissingPrefix"
    >
    <TextView
        安卓:textColor="@color/redText"
        安卓:textSize="37.14sp"
        安卓:layout_gravity="center_horizontal"
        安卓:gravity="center_vertical"
        安卓:textAlignment="center"
        安卓:layout_width="match_parent"
        安卓:layout_height="180dp"
        安卓:text="OBW"
        安卓:id="@+id/hindernisTypTextView"
        fontPath="DBSansRegular.otf"
        安卓:textAppearance="@style/DBSansRegular"
        安卓:background="@drawable/grid_view_item_selector"
        />
</RelativeLayout>

这是我的选择器

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:安卓="http://schemas.安卓.com/apk/res/安卓">
    <item 安卓:drawable="@color/redText" 安卓:state_pressed="true"/>
</selector>

下面是用于显示类别的片段

import 安卓.app.Activity;
import 安卓.app.Fragment;
import 安卓.app.FragmentManager;
import 安卓.app.FragmentTransaction;
import 安卓.content.Context;
import 安卓.os.Bundle;
import 安卓.view.LayoutInflater;
import 安卓.view.View;
import 安卓.view.ViewGroup;
import 安卓.widget.AdapterView;
import 安卓.widget.ArrayAdapter;
import 安卓.widget.GridView;
import 安卓.widget.Toast;

import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.adapters.HindernisTypGridViewAdapter;
import com.example.anikdey.railwayapp.models.HindernisTyp;



public class HindernisTypFragment extends Fragment {

    private GridView projectListGridView;
    private View view;

    private HindernisTyp hindernisTyp;
    private HindernisTypGridViewAdapter hindernisTypGridViewAdapter;
    private OnHindernisTypSelectedListener hindernisTypSelectedListener;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.kategorie_wahlen_grid_view, container, false);
        projectListGridView = (GridView) view.findViewById(R.id.kategoryWahlenGridView);
        hindernisTyp = new HindernisTyp();
        hindernisTypGridViewAdapter = new HindernisTypGridViewAdapter(getActivity().getApplicationContext(), hindernisTyp.getHindernisTyps());
        projectListGridView.setAdapter(hindernisTypGridViewAdapter);
        projectListGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                view.setSelected(true);
                hindernisTypSelectedListener.setHindernisTyp(hindernisTyp.getHindernisTyps().get(position).getHindernisTypName());
                FragmentManager fragmentManager = getActivity().getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container, new DetailsFragment(),"DetailsFragment");
                fragmentTransaction.addToBackStack("df");
                fragmentTransaction.commit();
            }
        });
        return view;
    }


}

我用于在gridview中显示类别的适配器

import 安卓.content.Context;
import 安卓.view.LayoutInflater;
import 安卓.view.View;
import 安卓.view.ViewGroup;
import 安卓.widget.BaseAdapter;
import 安卓.widget.ImageView;
import 安卓.widget.TextView;

import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.models.HindernisTyp;

import java.util.ArrayList;
import java.util.List;


public class HindernisTypGridViewAdapter  extends BaseAdapter {

    private Context context;
    private List<HindernisTyp> hindernisTyps = new ArrayList<HindernisTyp>();

    public HindernisTypGridViewAdapter(Context context, List<HindernisTyp> hindernisTyps){
        this.context = context;
        this.hindernisTyps = hindernisTyps;
    }

    @Override
    public int getCount() {
        return hindernisTyps.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    private static final class ViewHolder {
        private TextView hindernisTypTextView;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.hindernis_typ_grid_view_custom_layout, null, true);
            holder = new ViewHolder();
            holder.hindernisTypTextView = (TextView) convertView.findViewById(R.id.hindernisTypTextView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.hindernisTypTextView.setText(hindernisTyps.get(position).getHindernisTypName());

        return convertView;
    }
}

共 (2) 个答案

  1. # 1 楼答案

    当用户要将所选类别发送到主活动或共享首选项或常量,但不尝试依赖onSaveInstanceState()

    现在,当您从后堆栈返回到片段时,它不会重新创建片段,而是重新使用相同的实例,并在片段生命周期中从onCreateView()开始,请参见片段Lifecycle

    现在开始表格onCreateView() 因此,在片段中添加一个boolean isRestoredFromBackstack,并遵循下面的代码:

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        mIsRestoredFromBackstack = false;
    }
    
    @Override
    public void onResume()
    {
        super.onResume();
        if(mIsRestoredFromBackstack)
        {
            // The fragment restored from backstack, 
            // get selected state and set category selected again!
        }
    }
    
    @Override
    public void onDestroyView()
    {
        super.onDestroyView();
        mIsRestoredFromBackstack = true;
    }
    

    还有一个简单的解决方案。。。。视情况而定

    只要使用add()而不是replace()

    Fragment fragment=new DestinationFragment();
    FragmentManager fragmentManager = getFragmentManager();
    android.app.FragmentTransaction ft=fragmentManager.beginTransaction();
    ft.add(R.id.content_frame, fragment);
    ft.hide(SourceFragment.this);
    ft.addToBackStack(SourceFragment.class.getName());
    ft.commit();
    
  2. # 2 楼答案

    以下是我解决问题的方法。在开始新片段之前,我将位置存储在名为previousPosition的变量中,该变量被初始化为负值-1。然后我将通过适配器中的前一个位置。下面给出了代码

    更新的片段类

    package com.example.anikdey.railwayapp.fragments;
    
    import android.app.Activity;
    import android.app.Fragment;
    import android.app.FragmentManager;
    import android.app.FragmentTransaction;
    import android.content.Context;
    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.GridView;
    import android.widget.Toast;
    
    import com.example.anikdey.railwayapp.R;
    import com.example.anikdey.railwayapp.adapters.HindernisTypGridViewAdapter;
    import com.example.anikdey.railwayapp.models.HindernisTyp;
    
    
    public class HindernisTypFragment extends Fragment {
    
        private GridView projectListGridView;
        private View view;
    
        private HindernisTyp hindernisTyp;
        private HindernisTypGridViewAdapter hindernisTypGridViewAdapter;
        private OnHindernisTypSelectedListener hindernisTypSelectedListener;
    
        private int previousPosition = -1;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
            view = inflater.inflate(R.layout.kategorie_wahlen_grid_view, container, false);
            projectListGridView = (GridView) view.findViewById(R.id.kategoryWahlenGridView);
    
            hindernisTyp = new HindernisTyp();
            hindernisTypGridViewAdapter = new HindernisTypGridViewAdapter(getActivity().getApplicationContext(), hindernisTyp.getHindernisTyps(), previousPosition);
            projectListGridView.setAdapter(hindernisTypGridViewAdapter);
    
            projectListGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
                    hindernisTypSelectedListener.setHindernisTyp(hindernisTyp.getHindernisTyps().get(position).getHindernisTypName());
                    hindernisTypSelectedListener.enableCancelButton(true);
                    previousPosition = position;
                    FragmentManager fragmentManager = getActivity().getFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.fragment_container, new DetailsFragment(),"DetailsFragment");
                    fragmentTransaction.addToBackStack("df");
                    fragmentTransaction.commit();
                }
            });
            return view;
        }
    
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            try {
                hindernisTypSelectedListener = (OnHindernisTypSelectedListener) activity;
            } catch (ClassCastException e) {
    
            }
        }
    
        public interface OnHindernisTypSelectedListener {
            public void setHindernisTyp(String hindernisTyp);
            public void enableCancelButton(boolean state);
    
        }
    
    }
    

    下面是更新的适配器类

    package com.example.anikdey.railwayapp.adapters;
    
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    import com.example.anikdey.railwayapp.R;
    import com.example.anikdey.railwayapp.models.HindernisTyp;
    
    import java.util.ArrayList;
    import java.util.List;
    
    
    public class HindernisTypGridViewAdapter  extends BaseAdapter {
    
        private Context context;
        private int previousPosition;
        private List<HindernisTyp> hindernisTyps = new ArrayList<HindernisTyp>();
    
        public HindernisTypGridViewAdapter(Context context, List<HindernisTyp> hindernisTyps, int previousPosition){
            this.context = context;
            this.hindernisTyps = hindernisTyps;
            this.previousPosition = previousPosition;
    
        }
    
        @Override
        public int getCount() {
            return hindernisTyps.size();
        }
    
        @Override
        public Object getItem(int position) {
            return null;
        }
    
        @Override
        public long getItemId(int position) {
            return 0;
        }
    
        private static final class ViewHolder {
            private TextView hindernisTypTextView;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if(convertView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.hindernis_typ_grid_view_custom_layout, null, true);
                holder = new ViewHolder();
                holder.hindernisTypTextView = (TextView) convertView.findViewById(R.id.hindernisTypTextView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
    
            if(position == previousPosition) {
                holder.hindernisTypTextView.setBackgroundColor(context.getResources().getColor(R.color.redText));
                holder.hindernisTypTextView.setTextColor(context.getResources().getColor(R.color.whiteText));
                holder.hindernisTypTextView.setText(hindernisTyps.get(position).getHindernisTypName());
            } else {
                holder.hindernisTypTextView.setText(hindernisTyps.get(position).getHindernisTypName());
            }
    
            return convertView;
        }
    }