如何根据点击位置在GridView中选择TextView?

时间:2017-02-21 15:57:59

标签: java android android-fragments gridview

我正在使用一个片段,我使用GridView生成一些类别。当用户选择一个类别时,我用一个新片段替换前一个片段,该片段用于获取该类别的详细信息。但是当我回到上一个显示类别的片段时,我想要选择用户之前点击过的类别。我试过使用选择器,但它不适合我。这是我的代码。

这是我的布局xml文件

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

这是我对gridview的自定义xml

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

这是我的选择器

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

这是片段,用于显示类别

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;


    @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 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 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 个答案:

答案 0 :(得分:0)

当用户转到详细信息片段时,将所选类别发送到主要活动或共享偏好或常量但不尝试依赖onSaveInstanceState()

现在,当您从后台堆栈返回一个片段时,它不会重新创建片段,而是重新使用相同的实例,并在片段生命周期中以onCreateView()开头,请参阅片段phive (The PHAR Installation and Verification Environment)

现在开始表单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();

答案 1 :(得分:0)

这是我解决问题的方法。在开始新片段之前,我将位置存储在名为previousPosition的变量中,该变量初始化为负值-1。然后我在适配器中传递previousPosition。代码如下。

更新的Fragment类

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);

    }

}

这是更新的Adapter类

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;
    }
}